find a location for property in a new city

Tuesday 22 December 2015

Stop processing OPTIONS requests for CORS in ASP.NET Web API

I was attempting to allow some particular origins to access my ASP.NET Web API from a client side single page application. I was using the EnableCorsAttribute that comes with the Microsoft.AspNet.WebApi.Cors NuGet package.

I managed to set up CORS using the following code in my WebApiConfig:

var origins = ConfigurationManager.AppSettings["AllowedOrigins"];
var cors = new EnableCorsAttribute(origins, "accept,content-type,origin,customId", "GET,POST,PUT");
config.EnableCors(cors);

There is quite a lot to CORS but essentially, (some browsers) send a pre-flight request recognised with its HTTP method OPTIONS. This basically asks the application who is allowed to access this URL with the attempted headers and HTTP method. Your Web API will respond saying which origins are allowed or if there are any errors. The browser then decides if it is one of those allowed origins and sends the request if it is.

The problem I found is that on this initial OPTIONS request my IoC container, Unity, was constructing a whole dependency chain of classes. Some of which access the database and some check HTTP headers. This was throwing an error since bits were missing from the HTTP headers that would be with normal requests and unnecessarily hitting the database. So really, I wanted to stop these requests in their tracks whilst making sure they did their intended pre-flight work.

The best way I found to do this was to ignore routes based on an HTTP constraint for "OPTIONS". Basically shove this in your routing:

var constraints = new { httpMethod = new HttpMethodConstraint(HttpMethod.Options) };
config.Routes.IgnoreRoute("OPTIONS", "{*pathInfo}", constraints);

More info on Enabling CORS in Web API.

Follow britishdev on Twitter