Ajax 对Asp.Net Web API的角度Xhr post请求导致参数为空

Ajax 对Asp.Net Web API的角度Xhr post请求导致参数为空,ajax,angularjs,asp.net-web-api,http-post,Ajax,Angularjs,Asp.net Web Api,Http Post,我已经创建了一个ASP.NETAPI控制器,我正试图使用Angular向其发出POST请求。请求到达我的控制器方法,但参数值为null 我的角度代码: $http({ method: 'POST', url: '/api/Contents', data: "value=foobar", headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }). success(function(data) {

我已经创建了一个ASP.NETAPI控制器,我正试图使用Angular向其发出POST请求。请求到达我的控制器方法,但参数值为null

我的角度代码:

$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是我最终想要的):

我的(非常简单)控制器方法如下所示:

public void Post([FromBody]string value)
{
    //But Value is NULL!!!!!!
}
下面是我从Chrome中截取的请求头中的一些值(我认为这些值可能很有趣:

  • 申请方式:邮寄
  • 状态代码:204无内容
  • 接受:application/json、text/plain、/
  • 内容类型:application/x-www-form-urlencoded
  • X-request-With:XMLHttpRequest
  • 表单数据视图源视图URL编码
  • 值:foobar
  • 服务器:Microsoft IIS/8.0
  • X-AspNet-Version:4.0.30319
我错过了什么?

像这样:

$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
数据参数。在这种情况下不应指定参数名称。是的,我知道,不要问

<>你可以多读一点。如果你像我一样觉得这很疯狂,你可以考虑使用。

或者,也可以使用视图模型:

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字符串。

我使用的是上面的视图模型方法,但我的请求数据是视图模型对象的数组,Web Api将其设置为接受列表。当内容头设置为形成urlencoded和数据从Angular进入服务,我会得到一个计数为0的空对象。如果内容头设置为app/json,我会得到OPTIONS method not allowed error。如果我从Fiddler发送数据,内容类型会自动设置为content type:text/json;charset=utf-8,服务会接受它。你知道如何处理吗?
$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) {

});