Monday, February 16, 2015

WebAPI with CORS – IIS Intercepts OPTIONS Verb

Note: In this post, I'll ignore JSONP since it's a "workaround" to the topic. Also, CORS doesn't have anything to do with an Irish band.

When exposing a REST API, you have to consider whether you want to allow CORS or not. If you don't allow CORS (as of today, Twitter doesn't), then your API will have a "broken leg" since browsers, by default, will block the use of it:

(click to enlarge)

Browsers will issue a preflight request (OPTIONS) whenever you have an HTTP method that's not GET, POST or HEAD. Even when it is one of these, the browser will still issue the preflight request if you use specific/custom headers. You can read the specification here and you can see this request in the browsers developer tools.

Now, when using Web API to expose a REST API, enabling CORS is quite simple. There's a quick guide here: Enabling Cross-Origin Requests in ASP.NET Web API 2.
However, the guide isn't complete. If you're using IIS as your WebServer, this just won't be enough. That's because IIS, by default, has an Options handler that will intercept the HTTP request before it gets to your "WebAPI":

(click to enlarge)

So, you have to do a little workaround. In the web.config of your Application, just remove this Handler and add the Options processing to the ISAPI handler:

(click to enlarge)

Important note: By removing the Options handler and allowing the HTTPRequest to be processed by WebAPI, you also removed the handler when someone issues an OPTIONS request for any handler (e.g.: an ASP.NET Page). Other option is to change the priority of the OptionsVerb relative to the WebAPI handler. However, this WILL fill your web.config with all the handlers (at least in IIS7, 7.5 and 8).

Here's more info:
And here's a POST I created in the IIS forum for the ordering issue: