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!
The Cross-Origin Resource Sharing (CORS) specification consists of a simple header exchange between client-and-server, and is used by IE8's proprietary XDomainRequest object as well as by XMLHttpRequest in browsers such as Firefox 3.5 and Safari 4 to make cross-site requests.
So if you have an API that is designed to be only used by XHR, you can (and should) require the request to conform with CORS. Especially if the requests can also modify state on your server as otherwise you would be vulnerable to CSRF.
CORS is a W3C standard that allows you to get away from the same origin policy adopted by the browsers to restrict access from one domain to resources belonging to another domain. You can enable CORS for your Web API using the respective Web API package (depending on the version of Web API in use) or OWIN middleware.
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 !
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With