Enabling CORS in ASP.NET Web API

less than 1 minute read

The simplest way I’ve solved this is by adding below headers to all responses by adding them to Web.Config.

Just to state the obvious, when the client application and the server are both on localhost, the CORS issue doesn’t come into the pitcure.

Web.Config

...
<system.webServer>

  ...

  <httpProtocol>
     <customHeaders>
      <add name="Access-Control-Allow-Origin" value="http://<client>" />
      <add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" />
      <add name="Access-Control-Allow-Headers" value="content-Type, accept, origin, X-Requested-With, Authorization, name" />
      <add name="Access-Control-Allow-Credentials" value="true" />
     </customHeaders>
  </httpProtocol>

  ...

</system.webServer>
...

But this doesn’t respond appropriately to the OPTIONS request that most modern browsers send the server before making API calls to see if it can actually make API calls.

The server sends an empty response with the above headers set with the following code in Global.asax.cs:

Global.asax.cs

...

public class WebApiApplication : System.Web.HttpApplication
{
  ...

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

}
...

Leave a Comment