Wednesday, 1 November 2017

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

I have managed to overcome 405 and 404 errors thrown on pre-flight ajax options requests only by custom code in global.asax.

Step 1: Add following lines in web.config file.
 <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS" />
        <add name="Access-Control-Allow-Credentials" value="true"/>
        <add name="Access-Control-Allow-Headers" value="X-Requested-With, origin, content-type, accept" />
      </customHeaders>
    </httpProtocol>

Step 2: Add following code in Global.asax.cs file:
protected void Application_BeginRequest()
{
   if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}

No comments:

Post a Comment