Enable CORS in WebAPI 2
Step 1 – NuGet
On the WebAPI project, NuGet install the CORS package:
Install-Package Microsoft.AspNet.WebApi.Cors
Step 2 – Enable CORS
2.1 Global setup in WebApiConfig.cs
Inside the Register()
method, add in the CORS setting and enable it:
// Cors
var cors = new EnableCorsAttribute("*", "*", "GET"); // origins, headers, methods
config.EnableCors(cors);
Here we allow GET
method from any origin.
Or we can set up new EnableCorsAttribute("http://localhost, http://coderwall.com", "*", "GET, POST")
to allow GET
and POST
verbs from coderwall.com
or localhost
.
More details about this setting can be found in the W3 specifications page.
2.2 CORS Setup in specific ApiControllers
Instead of the global setting, we can also add in CORS support for specific ApiController
.
[EnableCors]
Additional parameters are allowed here also:
[EnableCors("*", "*", "GET")]
Of course, we can add this [EnableCors]
filter on either Controller
or Action
level. And it is possible to [EnableCors]
at the Controller
leveland place a
[DisableCors]` filter to exclude some of the actions.
Step 3 – Make Ajax Call from the Client Side
Just go ahead make an Ajax call. No difference from the local ajax calls.
If we are using jQuery
:
var getData = function () {
$.get(url).always(showResponse);
return false;
};
Note the response header of this GET
call:
Access-Control-Allow-Origin:*
Again, super easy to implement in WebAPI 2.
Written by Blaise Liu
Related protips
1 Response
It's very easy to set up and the topic is covered well.
What I can't seem to get working is POST to a CORS Enabled WebApi with Chrome. Actually, I can POST but I can POST with any data in the body of the post and without that I might as well only ever use the GET verb.
Any thoughts on this. I don't want to pollute the comments areas so I'll past a link to a broader description. if anyone has any ideas I would appreciate it.