Search code examples
c#asp.net-mvcasp.net-web-apicorshttp-status-code-405

Issues with CORS in ASP.NET


I have this App where I would like to set my custom headers in the Web.Config, alas this is not always fool proof.

  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="*" />
    <add name="Access-Control-Allow-Headers" value="*" />
  </customHeaders>

The above set and iterations of it such as

  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="OPTIONS,GET,PUT,DELETE,POST" />
    <add name="Access-Control-Allow-Headers" value="Authorization,Content-Type" />
  </customHeaders>

has not worked worked for me in all scenario's. As of now this setting works in about 50% of the test machines and gives 405 Method Not Allowed in others.

The alternative is set this in WebApiConfig.cs and uncomment the custom headers in Web.config.

//Web API Cross origin requests - Enable
  var cors = new EnableCorsAttribute("*", "*", "*");
  config.EnableCors(cors);

Why is there so much ambiguity in this and how do I know for sure where CORS will work all the time? I am really interested in setting CORS on Web.config only as I would like the flexibility of modifying it in the deployed version.


Solution

  • I believe that your 'random' issue occurs because you are not handling the preflight Options requests for PUT and Delete verbs.

    For the two verbs mentioned above an extra request is generated, Options, to which Web API needs to respond in order to confirm that it is indeed configured to support CORS.

    To handle this, all you need to do is send an empty response back. You can do this inside your actions, or you can do it globally like this:

    protected void Application_BeginRequest()
    {
        if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
        {
            Response.Flush();
        }
    }
    

    This extra check was added to ensure that old APIs that were designed to accept only GET and POST requests will not be exploited. Imagine sending a DELETE request to an API designed when this verb didn't exist. The outcome is unpredictable and the results might be dangerous.

    Also, in web.config, you should specify the methods instead of using *

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
     </httpProtocol>