【问题标题】:AngularJS $http provider not passing cookies to .NET Web ServiceAngularJS $http 提供程序未将 cookie 传递给 .NET Web 服务
【发布时间】:2013-05-14 13:01:57
【问题描述】:

我在使用 AngularJS 中的 $http 提供程序对需要身份验证的 .NET 后端进行 API 调用时遇到问题。 .NET 后端服务期望调用中包含“.ASPXAUTH”和“__RequestVerificationToken”cookie。

当我使用纯 JS 和 .ajax 时,在 beforesend 块中传递 cookie 是可行的。

$.ajax({
url: SERVER_URL + '/api/accounts',
type: 'GET',
dataType: 'json',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(data, status){
// ...
},
error: function (request, textStatus, errorThrown) {
// ...
},
beforeSend: function (req) {
    req.setRequestHeader("Cookie", REQUEST_VER_TOKEN);
    req.setRequestHeader("Cookie", ASPXAUTH_TOKEN);
}
});

在 AngularJS 中,我尝试在 $httpProvider 和 $http 调用中设置它但没有成功:

(在配置块中):

// ...
app.config(function ($routeProvider, $httpProvider) {
$httpProvider.defaults.headers.common[".ASPXAUTH"] = '....';
$httpProvider.defaults.headers.common["__RequestVerificationToken"] = '....';
$httpProvider.defaults.useXDomain = true; 
// ...

(在 $http 调用中):

  $http({ url: 'http://SERVER_URL/api/accounts', method: 'GET',
          {headers: {
          '__RequestVerificationToken': '....',
          '.ASPXAUTH': '....'
          }}
          })
.success(function(data, status, headers, config) {
    // ...
         })
.error(function (data, status, headers, config) {
    // ...
         });

我收到 401 Unauthorized 错误。如果从服务器代码中删除了 Authorization 块,则代码无需插入标头即可工作。如何在 AngularJS 中模拟相同的 beforesend 块并确保在 API 调用期间将 cookie 传递给服务器?

【问题讨论】:

  • 你找到解决这个问题的方法了吗?

标签: cookies angularjs http-headers


【解决方案1】:

您是否尝试将您的标头参数不是在 json 对象中而是直接传递到 headers 属性中?

$http({ url: 'http://SERVER_URL/api/accounts', method: 'GET',
      headers: {
      '__RequestVerificationToken': '....',
      '.ASPXAUTH': '....'
      }
}).success(function(data, status, headers, config) {
// ...
     })
.error(function (data, status, headers, config) {
// ...
});

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-25
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 2014-09-28
    相关资源
    最近更新 更多