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

我的梦境 提交于 2021-02-07 19:41:31

问题


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

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

On the webservice, the controller method looks like:

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

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>

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

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.

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.


回答1:


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

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.



来源:https://stackoverflow.com/questions/29210299/ajax-request-with-custom-header-sent-to-web-api-server-with-cors-enabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!