2013-04-22 72 views
4

我已經創建了一個ASP.Net API控制器,我試圖用Angular發出一個POST請求。請求到達我的控制器方法,但參數值爲空。Angular Xhr向Asp.Net Web API發送請求的結果參數爲空

我的角度代碼:

$http({ method: 'POST', url: '/api/Contents', data: "value=foobar", headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }). 
    success(function(data) { 
       }). 
    error(function(data, status, headers, config) { 

    }); 

我也試過用JSON(JSON是我想要的到底):

$http({ method: 'POST', url: '/api/Contents', data: { "foo": "bar", "foo2": "bar2" }, headers: { 'Content-Type': 'application/json'} }). 
    success(function(data) { 
       }). 
    error(function(data, status, headers, config) { 

    }); 

我的(很簡單)控制器方法是這樣的:

public void Post([FromBody]string value) 
{ 
    //But Value is NULL!!!!!! 
} 

下面是從我的請求頭的一些值從Chrome中切出(我想可能是內部的那些esting:

  • 請求方法:POST
  • 狀態代碼:204無內容
  • 接受:應用/ JSON,文本/純,/
  • 內容類型:應用程序/ x-WWW-窗體-urlencoded
  • X-請求-隨着:XMLHttpRequest的
  • 表格數據視圖sourceview URL編碼
  • 值:foobar的
  • 服務器:Microsoft-IIS/8.0
  • X-ASPNET-版本:4.0.30319

我缺少什麼?

回答

6

像這樣:

$http({ 
    method: 'POST', 
    url: '/api/Contents', 
    data: "=foobar", 
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' } 
}).success(function(data) { 

}).error(function(data, status, headers, config) { 

}); 

通知的=foobar數據參數。在這種情況下,您不應指定參數名稱。是的,我知道,不要問。

您可以閱讀更多關於how model binding in the Web API works。如果你和我一樣,發現這個絕對瘋了,你可以考慮使用ServiceStack

或者您可以使用視圖模型:

public class ContentsModel 
{ 
    public string Value { get; set; } 
} 

,然後讓你的控制器動作把視圖模型參數:

public void Post(ContentsModel model) 
{ 
} 

現在,您可以發送一個正常的JSON請求:

$http({ 
    method: 'POST', 
    url: '/api/Contents', 
    data: JSON.stringify({ "value": "the value" }), 
    headers: { 'Content-Type': 'application/json' } 
}).success(function(data) { 

}).error(function(data, status, headers, config) { 

}); 

另請注意,如果您想發送JSON,您需要使用JSON.stringify方法將JavaScript對象轉換爲JSON字符串。

+0

Thanx!所以很奇怪 - 但它的工作原理:-) B – Thea 2013-04-23 06:40:33

+0

我使用上面的視圖模型方法,但是我的請求數據是一個視圖模型對象數組,Web Api被設置爲列表。當內容標題設置爲表單urlencoded並且數據從Angular訪問服務時,我得到一個Count = 0的空對象。如果內容標頭設置爲app/json,我會得到OPTIONS方法不允許的錯誤。如果我從Fiddler發送數據,則內容類型設置爲Content-Type:text/json; charset = utf-8自動和服務接受它就好了。任何想法如何處理? – 2014-10-31 15:05:05