关于通过asp.net webservice检索数据,我遇到了一个奇怪的问题。
使用JQuery的ajax方法时,头文件设置正确,数据以JSON成功检索。
JSON示例:
$.ajax({
type: "GET",
url: "service/TestService.asmx/GetTestData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: callback,
error: function (err, xhr, res) {
alert(err);
}
});
上述请求标题如下:
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Type application/json; charset=utf-8
Host localhost
Referer http://localhost/
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
X-Requested-With XMLHttpRequest
上面的Reponse Headers如下:
Cache-Control private, max-age=0
Content-Length 327
Content-Type application/json; charset=utf-8
Date Tue, 29 Oct 2013 17:59:56 GMT
Server Microsoft-IIS/7.5
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET
这很好。
但是对于AngularJS $ http方法,未设置Request Headers Content-Type值,因此Response Headers Content-Type默认为text/xml; charset=utf-8
。看看下面的例子:
$http({
method : 'GET',
url: 'service/TestService.asmx/GetTestData',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/json; charset=utf-8'
}
}).success(callback);
上面的请求标题如下,您将看到缺少Content-Type:
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Host localhost
Referer http://localhost/ComponentsAndRepos/
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
因此上面的响应标题如下:
Cache-Control private, max-age=0
Content-Encoding gzip
Content-Length 341
Content-Type text/xml; charset=utf-8
Date Tue, 29 Oct 2013 17:59:56 GMT
Server Microsoft-IIS/7.5
Vary Accept-Encoding
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET
因此这会强制响应以XML而不是JSON的形式返回,有没有办法解决这个问题?
谢谢,
更新 感谢Erstad Stephen
通过将data:{}
属性添加到$http
方法已解决此问题。
$http({
method : 'GET',
url: 'service/TestService.asmx/GetTestData',
data: {},
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/json; charset=utf-8'
}
}).success(callback);
答案 0 :(得分:2)
您可以通过以下几种方式处理:
最重要的是你可能误解了配置的工作原理。在此处查看此问题:Angular, content type is not being generated correctly when using resource