无法使用角度正确设置自定义标头

时间:2015-01-07 11:38:48

标签: .net angularjs http-headers cors

我在启用了CORS的IIS上运行.net WebAPI项目。这个项目有一个授权处理程序,它在每个请求中检查一个名为“Token”的头,现在它只检查它是否有一个字符串值。

在我使用angular的API调用中,我使用以下行添加标题。我从角度文档中获取了这个

  

$ http.defaults.headers.common ['Token'] ='C3POR2D2';

来自fiddler的API原始数据如下。

OPTIONS http://localhost:81/api/Sample/GetSubordinateRolesForUser/1 HTTP/1.1
Host: localhost:81
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)     Chrome/40.0.2214.45 Safari/537.36
Access-Control-Request-Headers: accept, token
Accept: */*
Referer: http://localhost/Account/Login
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

此处'token'在Access-Control-Request-Headers下显示为一个值。这导致我的授权处理程序返回403 Forbidden,因为它期望标题'Token'具有一些字符串值。

以下是响应原始数据

HTTP/1.1 403 Forbidden
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Access-Control-Allow-Headers: Token
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Date: Wed, 07 Jan 2015 11:28:43 GMT
Content-Length: 0

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

使用它。我也面临类似的问题

function getSettings(requestData) {
    return {
        url: requestData.url,
        dataType: requestData.dataType || "json",
        data: requestData.data || {},
        headers: requestData.headers || {
            "accept": "application/json; charset=utf-8",
            'Authorization': requestData.token
        },
        async: requestData.async || "false",
        cache: requestData.cache || "false",
        success: requestData.success || {},
        error: requestData.error || {},
        complete: requestData.complete || {},
        fail: requestData.fail || {}
    };
}

并以这种方式调用

    var requestData = {
        url: 'your API end point',
        data: project,
        token: yourtoken
    };

    var settings = getSettings(requestData);
    settings.method = "POST"; //Your request
    return $http(settings);

并删除$ http.defaults.headers.common ['令牌'] =' C3POR2D2';