无法从 Web API 中的 jQuery AJAX 请求获取标头 ASP.NET



我有一个托管在Azure上的 ASP.NET Web API。我已经将HTTP消息处理程序集成到该API中。当我使用 AJAX 调用击中消息处理程序时,消息处理程序受到攻击。我还在 AJAX 调用中发送了一些请求标头。问题是我没有从 AJAX 调用发送到 Web API 中集成的消息处理程序的标头。参考图片:调试器屏幕截图

以下是我的 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客户端,请求工作正常,但从本地主机返回错误。请让我知道在我的消息处理程序中没有获得标头的原因?

您必须在 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 请求,以确保允许您执行该请求。正如错误所说,"对预检请求的响应未通过访问控制检查:请求的资源上不存在'访问控制-允许源'标头。在 Web.config 中添加上述行将传递所需的标头。

MDN说:"与简单请求(上面讨论过(不同,"预检"请求首先向其他域上的资源发送HTTP OPTIONS请求标头,以确定实际请求是否可以安全发送。跨站点请求是像这样预检的,因为它们可能会对用户数据产生影响。

试试这个

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

相关内容

  • 没有找到相关文章

最新更新