启用了CORS的带有自定义标头的Ajax请求发送到Web API服务器 [英] Ajax request with custom header sent to Web API server with CORS enabled

查看:56
本文介绍了启用了CORS的带有自定义标头的Ajax请求发送到Web API服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试正确设置Web API Web服务以使用CORS,但最近运气不高.

I'm trying to get a Web API webservice setup correctly to use CORS but haven't been having much luck with it lately.

我有一个来自移动应用程序的html页面,该页面使用ajax请求来获取一些数据:

I have an html page from a mobile app using an ajax request to fetch some data:

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无法加载http://..urlGoesHere ../getuserlevel/2B65FA52?BlackberryPin=2B65FA52&_=1427109244103.所请求的资源上没有"Access-Control-Allow-Origin"标头.因此,不允许访问来源" http://localhost:3726 .响应的HTTP状态代码为404.

XMLHttpRequest cannot load http://.. urlGoesHere ../getuserlevel/2B65FA52?BlackberryPin=2B65FA52&_=1427109244103. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3726' is therefore not allowed access. The response had HTTP status code 404.

在Web服务上,控制器方法如下:

On the webservice, the controller method looks like:

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

我在Web服务的web.config中启用了CORS,如下所示:

I have CORS enabled in the web.config of my webservice as so:

<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>

我们的Web api配置非常简单:

Our web api config is fairly simple:

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());            
    }
}

我们已经设置了一个网络授权过滤器,以检查自定义标头"BlackberryPin",并将拒绝不包含该标头和有效品脱的请求.在使用远程调试器测试Web服务时,我发现它没有到达授权过滤器代码,因此我怀疑这里的路由/CORS配置有问题.

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. 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.

感谢您提供的任何帮助或想法.

Thanks for any help or ideas you can give.

更新:

我还在控制器方法上尝试了以下数据注释:

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

当我使用提琴手调用此方法(作为GET)时,它成功通过.但是,使用ajax调用会在预检OPTIONS请求上返回405错误,该请求在主GET调用之前发送.

When I use fiddler to call this method (as a GET) it successfully gets through. However using the ajax call it returns a 405 error on the preflight OPTIONS request which is sent before the main GET call.

推荐答案

仔细查看Firebug中ajax OPTIONS调用中的请求标头.

Had a closer look at the request headers in the ajax OPTIONS call in Firebug.

事实证明,我错过了web.config中配置键Access-Control-Allow-Headers下的一些可接受的标头.我添加了以下标头:Accept,Accept-Encoding,Accept-Language,Cache-Control,Access-Control-Request-Header,Access-Control-Request-Method.

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. I added the headers: Accept, Accept-Encoding, Accept-Language, Cache-Control, Access-Control-Request-Header, Access-Control-Request-Method.

这篇关于启用了CORS的带有自定义标头的Ajax请求发送到Web API服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆