Just wanted to know what is the best elegant way (currently available) to handle CORS (Cross-Origin Resource Sharing) in ASP.NET WebAPI so i can use XmlHttpRequest over multiple domains ? How i can integrate this in the headers of every type of request (GEt, POST, etc..) with OPTIONS too ?
Thanks!
Add below in web.cofig file(inside the system.webserver element).
and add below code in global.aspx.cs file
It depends how fine-grained you want to control CORS. If you want to allow any domain for instance you can add static CORS headers to all responses by configuring them in IIS. I chose this approach and wrote about it here.
Carlos Figueira has a nice series of posts about CORS and ASP.NET Web API:
Personally I'm a big fan of Take 2 approach because
EnableCors
attribute can be easly extended to give you control over allowed origins.There is now CORS support in the nightly of web api
http://blogs.msdn.com/b/yaohuang1/archive/2013/04/05/try-out-asp.net-web-api-cors-support-using-the-nightly-builds.aspx
Use nuget to:
Then fix the bindings in the web.config Then enable CORS
Read more about it on this wiki https://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API&referringTitle=Specs
Edit 19-04-2013 Scott Guthrie has blogged about it: http://weblogs.asp.net/scottgu/archive/2013/04/19/asp-net-web-api-cors-support-and-attribute-based-routing-improvements.aspx
Tpeczek have a nice found, however while doing my own research ive found something similar and also very elegant ways of handling CORS which enable you to configure your CORS in a config file in App_Start folder. Its all handled using an open source library called Thinkecture. See details here :
http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/
It have many advantages.. you can configure origins, methods (GET, POST, etc.), access to specifics controllers and actions and it also keep your controllers clean from any attributes.
WebAPI, IIS and ASP.NET MVC is supported !