Support pre-flight OPTIONS requests in .Net WebAPI

A way to support the ‘OPTIONS’ pre-flight request in .net WebAPI is to by-pass this request with a default response and returning the required Headers.

Add the below code in your Global.asax.cs file under the Application_BeginRequest method:

protected void Application_BeginRequest()
{
	if (Request.HttpMethod == "OPTIONS")
	{
		HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
		HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, expiry, id, token, token-type");
		HttpContext.Current.Response.AddHeader("Access-Control-Allow‌​-Credentials", "true");
		HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
		HttpContext.Current.Response.End();
	}
}

So when you call the WebAPI with Javscript fetch/axios, the pre-flight request sent before the actual request would get the 200 status code.

The example above shows some sample custom headers and allowed methods that will be returned in Response Headers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.