2016-09-20 68 views
0

我有下面的模型類的WebAPI: -發送數據的WebAPI GET請求Ajax調用

public class SampleClass 
    { 
     public int id { get; set; } 
     public string Name { get; set; } 
    } 

Get方法在控制器: -

public string Get([FromBody]SampleClass sample) 
     { 
      return "value"; 
     } 

我打電話從應用程序通過Ajax這種獲取方法呼叫爲: -

var source = { 
       'id': 0, 
       'Name': 'sagar' 
      }    

      $.ajax({ 
       type: "GET", 
       dataType: "json", 
       url: "http://localhost:51366/api/Values", 
       data: source, 
       success: function (data) { 
        alert(data); 
       }, 
       error: function (error) { 

        jsonValue = jQuery.parseJSON(error.responseText); 
        alert("error" + error.responseText); 
       } 
      }); 

方法被調用,但獲得SampleClass對象爲空 卜t我發送了id爲0,名稱爲sagar。它應該檢索這些值而不是null。

enter image description here

+2

[HttpGet]不包含正文,爲什麼你不能訪問它,你需要使用[HttpPost] –

回答

3
  1. 馬克服務器法HttpPost
  2. 「POST」 數據

在服務器...

[HttpPost] 
public string Get([FromBody]SampleClass sample) 

在客戶端上...

  $.ajax({ 
       type: "POST", 
       dataType: "json", 
       url: "http://localhost:51366/api/Values", 
       data: source, 
       success: function (data) { 
        alert(data); 
       }, 
       error: function (error) { 

        jsonValue = jQuery.parseJSON(error.responseText); 
        alert("error" + error.responseText); 
       } 
      }); 

編輯 - 不推薦:

以避免對身體的需要,讓你「HTTPGET」將數據發送到服務器把它的查詢字符串這樣的...

$.ajax({ 
        type: "GET", 
        dataType: "json", 
        url: "http://localhost:51366/api/Values?id=" + source.id + "&Name=" + source.Name, 
        success: function (data) { 
         alert(data); 
        }, 
        error: function (error) { 

         jsonValue = jQuery.parseJSON(error.responseText); 
         alert("error" + error.responseText); 
        } 
       }); 
+0

但我想這個HTTPGET –

+0

你不能發佈數據在一個GET的正文HTTP協議doesn沒有那樣的工作......但好的......這是什麼意思? – War