Jam*_*Orr 5 asp.net-web-api angularjs
我已经用jQuery编写针对ASP.NET Web API的代码了一段时间,我在Angular中开始了一些新的东西(针对相同的Web API后端编写.)
我正在发布一个方法,该方法将返回系统中实体的一些搜索结果.它看起来像这样:
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.
}
Run Code Online (Sandbox Code Playgroud)
如果我使用jQuery.post调用该方法:
$.post('api/search/child', {where : 'ParentID = 1'}, function(d){ foo = d });
Run Code Online (Sandbox Code Playgroud)
它运作正常,并返回我期望的.
我在我的角度应用程序中提供了一个类似的调用服务:
$http.post('api/search/child', { where: 'parentID = ' + parent.ID })
.success(function (data, status, headers, config) {
// etc.
})
Run Code Online (Sandbox Code Playgroud)
但是当它在服务器上点击我的"Post"方法时,"paramters"为空.
经过一些谷歌搜索后,我尝试添加一个内容类型的标题,以确保它作为JSON传递,并尝试JSON.stringify-ing和$ .param() - "数据"参数,但没有做任何事情(和从我所读到的那些不应该是必要的.)我在这里做错了什么?谢谢你的帮助!
更新:这是来自(工作)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
Run Code Online (Sandbox Code Playgroud)
来自(失败的)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"}
Run Code Online (Sandbox Code Playgroud)
很奇怪.即使我将'json'数据类型参数添加到jQuery调用的末尾,它仍然会创建www-form-urlencoded请求.那是有效的.我的Web API应用程序已经为JSON设置(但感谢Dalorzo).
解决了!发现了这个问题:
指向这篇可爱的文章:
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
事实证明,Angular 发布数据的方式与 jQuery 不同,但您可以通过一些调整来覆盖它。
| 归档时间: |
|
| 查看次数: |
24738 次 |
| 最近记录: |