简体   繁体   English

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

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

I have an ASP.NET Web API which is hosted on Azure. 我有一个托管在Azure上的ASP.NET Web API。 I have integrated HTTP Message handler to that API. 我已经将HTTP消息处理程序集成到该API。 The message handler is getting hit when I am hitting it using AJAX call. 使用AJAX调用时,消息处理程序被击中。 I am also sending some request header in my AJAX call. 我还在AJAX调用中发送了一些请求标头。 The problem is I am not getting header sent from AJAX call to Message Handler integrated in Web API. 问题是我没有从AJAX调用将标头发送到Web API中集成的消息处理程序。 Refer image: Debugger screenshot 参考图片: 调试器屏幕截图

Below is the code of my AJAX request: 以下是我的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);
    }
});

The message handler in Web API looks like below: 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;
    }
}

When I run the the code from my IIS localhost the request which is sent is something like below: 当我从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

And the response which I getting in console is: 我在控制台中得到的响应是:

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.

With POSTMAN client the request works fine but from localhost it returns an error. 使用POSTMAN客户端,请求可以正常运行,但是从本地主机返回错误。 Please let me know the reason for not getting header in my message handler? 请让我知道未在邮件处理程序中获取标头的原因吗?

You have to add this in your Web.config (you can change values as you need): 您必须在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>

Before your request, an OPTIONS request is sent to ensure that you are allowed to perform the request. 在您发出请求之前,将发送一个OPTIONS请求,以确保您被允许执行该请求。 As the error says, "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.". 如错误所述:“对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头。”。 Adding above lines in Web.config will pass the needed header. 在Web.config中添加以上行将传递所需的标头。

MDN says: "Unlike simple requests (discussed above), "preflighted" requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data." MDN说:“与简单的请求(如上所述)不同,“预检”的请求首先将HTTP OPTIONS请求标头发送到另一个域上的资源,以确定实际请求是否可以安全发送。跨站点的请求被预检之所以这样,是因为它们可能会对用户数据产生影响。”

Try this 尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM