无法从 jQuery AJAX 请求 ASP.NET Web API 中获取 headers

Unable to get headers from jQuery AJAX request in ASP.NET Web API

我有一个托管在 Azure 上的 ASP.NET Web API。我已经将 HTTP 消息处理程序集成到那个 API。当我使用 AJAX 调用点击它时,消息处理程序被点击。我还在 AJAX 电话中发送了一些请求 header。问题是我没有从 AJAX 调用发送到 Web API 中集成的消息处理程序 header。参考图片:Debugger screenshot

下面是我的 AJAX 请求的代码:

$.ajax({
    url: "https://someservicename.azurewebsites.net/Service/RequestHandler",
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Token', '86810e135958961ad4880ad');
    },
    type: "POST",
    crossDomain: true,
    data: {
        param: "Passed Parameter"
    },
    success: function (msg) {
        console.log(msg);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(textStatus);
    }
});

Web 中的消息处理程序 API 如下所示:

protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    string authToken;
    try
    {
        authToken = request.Headers.GetValues("Token").FirstOrDefault();

        if (authToken != "86810e135958961ad4880ad")
        {

            return await Task.Factory.StartNew(() =>
            {
                return new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Unauthorized access!")
                };
            });
        }
        else
        {
            return await base.SendAsync(request, cancellationToken);
        }
    }
    catch (System.InvalidOperationException)
    {
        return null;
    }
}

当我 运行 来自我的 IIS 本地主机的代码时,发送的请求如下所示:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:token
Access-Control-Request-Method:POST
Connection:keep-alive
Host:someservicename.azurewebsites.net
Origin:http://localhost:12522
Referer:http://localhost:12522/pocppd.html
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36

我在控制台中得到的响应是:

https://someservicename.azurewebsites.net/Service/RequestHandler. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:12522' is therefore not allowed access. The response had HTTP status code 500.

使用 POSTMAN 客户端请求工作正常,但从本地主机请求 returns 错误。请告诉我在我的消息处理程序中没有得到 header 的原因?

您必须在 Web.config 中添加此内容(您可以根据需要更改值):

    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization, Token" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
        </customHeaders>
    </httpProtocol>

在您提出请求之前,系统会发送一个 OPTIONS 请求以确保您可以执行该请求。正如错误所说,"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."。在 Web.config 中添加以上行将传递所需的 header.

MDN 说:"Unlike simple requests (discussed above), "preflighted" 请求首先发送 HTTP OPTIONS 请求 header 到其他域上的资源,以确定实际请求是否可以安全发送。 Cross-site 请求像这样进行预检,因为它们可能对用户数据有影响。"

试试这个

$.ajax({
    url: "https://someservicename.azurewebsites.net/Service/RequestHandler",
    headers: {
            "Token": "86810e135958961ad4880ad"
        },    
    type: "POST",
    crossDomain: true,
    data: {
        param: "Passed Parameter"
    },
    success: function (msg) {
        console.log(msg);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(textStatus);
    }
});