In this age of APIs and the 'Internet of Things', a client might request many resources across hosts. Most browsers implement an array of security around these requests, for hopefully obvious reasons. CORS is a standard mechanism which allows web servers to designate access controls for cross-domain requests with a few HTTP headers. At first glance, it appears like a lot of work since it requires every non-GET
resource to respond to an OPTIONS
request. Luckily a lot of frameworks have built-in methods or plugins that will easily work out what's needed and hook it all up; this post describes the easiest way of setting it up in Microsoft's ASP.NET Web API.
First, install the nuget package:
Install-Package Microsoft.AspNet.Cors
Then enable it by calling the EnableCors
extension method on the application's HttpConfiguration
instance that's available during startup —a good place is often WebApiConfig.cs
, usually found under App_Start
:
public static void Register(HttpConfiguration config)
{
// Enable CORS
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
// Default routes
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Controllers or actions may now be annotated with the EnableCors
attribute to open them to CORS requests. It accepts three parameters, all comma-separated strings: the allowed origins, headers and methods, in that order. Null or empty strings mean nothing is accepted—use "*"
to allow anything.
[EnableCors("my.host.io,test.host.io", "*", "GET,POST,PUT")]
public DataController : ApiController
{
//...
}
After that it's just a case of fixing any remaining issues by ensuring exposed methods are marked with the correct allow-verb attributes—HttpGetAttribute
and friends—if not infered correctly.