Enabling CORS in ASP.NET Web API
I found myself having to create a completely REST-enabled API for an in-house solution, so what better way to do this in .NET than leveraging ASP.NET Web API?
While Web API makes mostly everything about the process simple and easy, considering that this is going to be a full-fledged REST API, I had to consider allowing cross-domain requests to the API, which normally meant that I had to enable cross-origin resource sharing (CORS) on it.
I found a nice handful of good resources for ASP.NET Web API CORS support, but I found Carlos Figueira’s take on it the most helpful, so I went ahead and adapted his code into my own small AOP library for use with future projects.
Using the library should be as easy as just adding
[CorsEnabled] on your API actions and/or controllers. It provides a bit of additional functionality if you need it (like specifying allowed domains if you want).
Feel free to get the code here. I wholeheartedly welcome comments on it, and if you find that you want to fork it, be my guest.