gpt4 book ai didi

asp.net - 将 AngularJS $http 与 asp.net webservice 一起使用,有没有办法设置请求 header ?

转载 作者:行者123 更新时间:2023-12-02 21:02:57 26 4
gpt4 key购买 nike

我刚刚遇到了一个关于通过 asp.net Web 服务检索数据的奇怪问题。

使用 JQuery 的 ajax 方法时, header 设置正确,并且成功以 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);
}
});

上述请求 header 如下:

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

上述响应 header 如下:

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 方法,未设置请求 header 内容类型值,因此响应 header 内容类型默认为 text/xml;字符集=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);

上面的请求 header 如下,您将看到缺少 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

因此上述响应 header 如下:

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 的形式返回,有办法解决这个问题吗?

谢谢,

更新感谢埃斯塔德·斯蒂芬

通过向 $http 方法添加 data:{} 属性已解决此问题。

    $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);

最佳答案

您可以通过几种不同的方式来处理这个问题:

  1. 您可以通过 $httpProvider 设置 header 默认值:http://docs.angularjs.org/api/ng .$http#description_setting-http-headers
  2. 您还可以使用 Angular 中的拦截器来拦截 $http 的想法,以修改所有请求的配置对象:http://docs.angularjs.org/api/ng .$http#description_interceptors
  3. 您还可以像上面那样设置配置设置。

最重要的是你可能误解了配置的工作原理。在这里查看这个问题:Angular, content type is not being generated correctly when using resource

关于asp.net - 将 AngularJS $http 与 asp.net webservice 一起使用,有没有办法设置请求 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19666167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com