AngularJS http请求不会为CORS发送会话cookie

时间:2014-12-13 07:33:49

标签: angularjs asp.net-web-api cors session-cookies

我的脚本是:

<script>
        function eventController($scope, $http) {  
            $http.get("http://example.com/api/Event", {withCredentials: true})
                .success(function (response) {
                    $scope.events = response;
                });
        }
</script>

来自Fiddler的请求标题:

GET http://example.com/api/Event HTTP/1.1
Host: example.com
Connection: keep-alive
Cache-Control: max-age=0
Accept: application/json, text/plain, */*
Origin: http://www.example.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
Referer: http://www.example.com/Home/Event
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

我需要使用此请求发送身份验证会话Cookie。

只有在网页的网址前面没有www时才会发送cookie。

我在这个网站上发现了一个类似的问题,答案是:

.config(function ($routeProvider, $httpProvider) {
    $httpProvider.defaults.withCredentials = true;
    //rest of route code

但是我将这段代码放在我的脚本中?

我正在开发的Web应用程序是一个带有Web Api 2的ASP.NET MVC5应用程序。

2 个答案:

答案 0 :(得分:0)

需要将配置注入角度模块,如下所示:

// get an existing module by name
var app = angular.module('app');

// inject $httpProvider configuration
app.config(function ($httpProvider) {
  $httpProvider.defaults.withCredentials = true;
});

答案 1 :(得分:0)

事实证明我的AngularJS脚本运行正常(只需将{withCredentials:true}作为$ http.get方法中的参数传递)。出了什么问题是我的MVC应用程序没有在子域中存储会话cookie。所以我通过在CookieAuthenticationOptions中添加CookieDomain来修复它。