angularjs – Angular POST to Web API不传递数据
我已经用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. } 如果我使用jQuery.post调用该方法: $.post('api/search/child',{where : 'ParentID = 1'},function(d){ foo = d }); 它运作正常,并返回我期望的. 我在我的角度应用程序中提供了一个类似的调用服务: $http.post('api/search/child',{ where: 'parentID = ' + parent.ID }) .success(function (data,status,headers,config) { // etc. }) 但是当它在服务器上点击我的“Post”方法时,“paramters”为空. 经过一些谷歌搜索后,我尝试添加一个内容类型的标题,以确保它作为JSON传递,并尝试JSON.stringify-ing和$.param() – “数据”参数,但没有做任何事情(和从我所读到的那些不应该是必要的.)我在这里做错了什么?谢谢你的帮助! 更新: 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 Formatter.它应该是这样的:
System.Web.Http.GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); config.Formatters.Insert(0,new System.Net.Http.Formatting.JsonMediaTypeFormatter()); 只有设置了正确的格式化程序,Content-Type = application / json才有效. 您也可以尝试在参数类型旁边使用[FromBody]. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |