我已经使用 jQuery 针对 ASP.NET Web API 编写代码有一段时间了,并且我正在 Angular 中开始一些新的东西(针对相同的 Web API 后端编写。)
我正在 POST 到一个方法,该方法将返回系统中实体的一些搜索结果。它看起来像这样:
public IEnumerable<dynamic> Post(string entity, FormDataCollection parameters)
{
// entity is passed on the route.
// parameters contains all the stuff I'm trying to get here.
}
如果我使用 jQuery.post 调用该方法:
$.post('api/search/child', {where : 'ParentID = 1'}, function(d){ foo = d });
它工作得很好并且返回了我所期望的结果。
我在我的 Angular 应用程序中创建了一个服务来进行类似的调用:
$http.post('api/search/child', { where: 'parentID = ' + parent.ID })
.success(function (data, status, headers, config) {
// etc.
})
但是当它到达服务器上的“Post”方法时,“paramters”为空。
经过一些谷歌搜索后,我尝试添加一个内容类型 header 以确保它作为 JSON 传递,并尝试 JSON.stringify-ing 和 $.param()-ing “data”参数,但这并没有做任何事情(从我读到的内容来看,这应该是不必要的。)我在这里做错了什么?感谢您的帮助!
更新: 这是来自(工作)jQuery 示例的原始请求:
POST http://localhost:51383/api/search/child HTTP/1.1
Accept: */*
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:51383/mypage.aspx
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Host: localhost:51383
Content-Length: 23
DNT: 1
Connection: Keep-Alive
Pragma: no-cache
Cookie: (etc)
Authorization: (etc)
where=ParentID+%3D+1
来自(失败的)Angular 示例的原始请求:
POST http://localhost:51383/api/search/parent HTTP/1.1
Content-Type: application/json;charset=utf-8
Accept: application/json, text/plain, */*
Referer: http://localhost:51383/mypage.aspx
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
Content-Length: 27
DNT: 1
Host: localhost:51383
Pragma: no-cache
Cookie: (etc)
{"where":"ScorecardID = 1"}
很奇怪。即使我将“json”数据类型参数添加到 jQuery 调用的末尾,它仍然会创建 www-form-urlencoded 请求。这就是有效的方法。我的 Web API 应用程序已经设置为 JSON(但谢谢 Dalorzo)。
最佳答案
检查您的配置中是否包含 JSON 格式化程序。它应该是这样的:
System.Web.Http.GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
config.Formatters.Insert(0, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
只有设置正确的格式化程序,Content-Type=application/json
才会起作用。
您还可以尝试在参数类型旁边使用 [FromBody]。
关于angularjs - Angular POST 到 Web API 不传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23925540/