简体   繁体   English

带有自定义标头的Ajax请求已发送到启用了CORS的Web API服务器

[英]Ajax request with custom header sent to Web API server with CORS enabled

I'm trying to get a Web API webservice setup correctly to use CORS but haven't been having much luck with it lately. 我正在尝试正确设置Web API Web服务以使用CORS,但最近并没有太多运气。

I have an html page from a mobile app using an ajax request to fetch some data: 我有一个来自移动应用程序的html页面,使用ajax请求来获取一些数据:

Webservices.GetUserLevel = function() {
    var userLevel = null;

    $.ajax({
        url: _CONNECTION_STRING + "getuserlevel/" + _USER_PIN,
        contentType:'application/json; charset=utf-8',
        type: 'GET',
        async: false,
        cache: false,
        crossDomain: true,        
        data: {
            BlackberryPin: _USER_PIN
        },
        beforeSend: function(xhr) {
            xhr.setRequestHeader('BlackberryPin', _USER_PIN);                   
        },
        success: function(data) {
            userLevel = data;
        },
        error: function(xhr, ajaxOptions, thrownError) {
            Webservices.HandleError(xhr, ajaxOptions, thrownError);
        }
    });

    return userLevel;
}

The response I get from that call is: 我从该电话中得到的回应是:

XMLHttpRequest cannot load http://.. urlGoesHere ../getuserlevel/2B65FA52?BlackberryPin=2B65FA52&_=1427109244103. XMLHttpRequest无法加载http:// .. urlGoesHere ../getuserlevel/2B65FA52?BlackberryPin=2B65FA52&_=1427109244103。 No 'Access-Control-Allow-Origin' header is present on the requested resource. 请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin ' http://localhost:3726 ' is therefore not allowed access. 因此不允许来源' http:// localhost:3726 '访问。 The response had HTTP status code 404. 响应具有HTTP状态代码404。

On the webservice, the controller method looks like: 在Web服务上,控制器方法如下所示:

public UserLevel GetUserLevel(string pin)
{    
    return _service.GetUserLevel(pin);
}

I have CORS enabled in the web.config of my webservice as so: 我在webservice的web.config中启用了CORS,如下所示:

<system.webServer>            
<validation validateIntegratedModeConfiguration="false" />
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Authorization, Accept, X-Requested-With, Origin, BlackberryPin" />
    <add name="Access-Control-Allow-Methods" value="OPTIONS, TRACE, GET, HEAD, POST, PUT" />
  </customHeaders>

</httpProtocol>
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>    
</system.webServer>

Our web api config is fairly simple: 我们的web api配置非常简单:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Filters.Add(new HandleExceptionAttribute());
        config.Filters.Add(new WebAuthorisationFilter());            
    }
}

There is a web authorization filter we've set up to check for the custom header 'BlackberryPin' and will reject requests that don't contain that header and a valid pint. 我们设置了一个Web授权过滤器来检查自定义标头“BlackberryPin”,并拒绝不包含该标头和有效品脱的请求。 On testing the webservice with the remote debugger I found that it isn't getting to the authorization filter code so I suspect it is the routing/CORS configuration at fault here. 在使用远程调试器测试web服务时,我发现它没有获得授权过滤器代码,所以我怀疑这是路由/ CORS配置有问题。

Thanks for any help or ideas you can give. 感谢您提供的任何帮助或想法。

Update: 更新:

I've also tried the following data annotations on the controller method: 我还在控制器方法上尝试了以下数据注释:

    [Route("api/erouter/GetUserLevel/{pin}")]        
    [EnableCors("*", "Accept, Origin, Content-Type, OPTIONS, Pin, BlackberryPin", "GET")]
    public UserLevel GetUserLevel(string pin)
    {    
        return _service.GetUserLevel(new ERouterRequest(pin,null));
    }

When I use fiddler to call this method (as a GET) it successfully gets through. 当我使用fiddler调用此方法(作为GET)时,它成功通过。 However using the ajax call it returns a 405 error on the preflight OPTIONS request which is sent before the main GET call. 但是,使用ajax调用它会在预检OPTIONS请求中返回405错误,该请求在主GET调用之前发送。

Had a closer look at the request headers in the ajax OPTIONS call in Firebug. 仔细看看Firebug中ajax OPTIONS调用中的请求标头。

It turns out I had missed out a few of the accepted headers in my web.config under the config key Access-Control-Allow-Headers. 事实证明,我在配置密钥Access-Control-Allow-Headers下的web.config中错过了一些可接受的标题。 I added the headers: Accept, Accept-Encoding, Accept-Language, Cache-Control, Access-Control-Request-Header, Access-Control-Request-Method. 我添加了标题:Accept,Accept-Encoding,Accept-Language,Cache-Control,Access-Control-Request-Header,Access-Control-Request-Method。

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

相关问题 启用CORS的Web API无法添加标头 - CORS enabled Web API fails to add header c#已启用CORS的Web Api和所请求资源上存在可怕的“Access-Control-Allow-Origin”标头 - c# Web Api with CORS Enabled and the dreaded No 'Access-Control-Allow-Origin' header is present on the requested resource 使用 Windows 身份验证的已启用 CORS ASP.NET Web API 2 应用程序中的预检请求 - preflight request in enabled CORS ASP.NET Web API 2 application with windows authentication 仅当启用cors时,asp.net Web API POST请求的400响应 - 400 Response for asp.net web api POST request only when cors is enabled Web API 2 Cors请求错误 - Web API 2 Cors Request Error Web API 2.0上的CORs请求 - CORs Request on Web API 2.0 接受通过 ajax 在 Post 请求中发送的 web API (C#) 中的 ArrayBuffer(不使用表单) - Accept ArrayBuffer in web API (C#) sent in Post request via ajax (Without use of form) Web API 2 CORS不存在“ Access-Control-Allow-Origin”标头 - web api 2 CORS No 'Access-Control-Allow-Origin' header is present CORS 带有启用选项 Header on ASP Net Core 5 Web Z72664DC0959F877C043891 - CORS With Enable OPTIONS Header on ASP Net Core 5 Web Api 在 .NET 核心 Web API 上为 CORS 启用选项 header - Enable OPTIONS header for CORS on .NET Core Web API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM