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

时间:2021-06-09 15:20:59

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

XMLHttpRequest无法加载http:// .. urlGoesHere ../getuserlevel/2B65FA52?BlackberryPin=2B65FA52&_=1427109244103。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许来源“http:// localhost:3726”访问。响应具有HTTP状态代码404。

On the webservice, the controller method looks like:

在webservice上,控制器方法如下所示:

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. 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授权过滤器来检查自定义标头“BlackberryPin”,并拒绝不包含该标头和有效品脱的请求。在使用远程调试器测试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. However using the ajax call it returns a 405 error on the preflight OPTIONS request which is sent before the main GET call.

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

1 个解决方案

#1


2  

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

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

#1


2  

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

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