Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS with WebAPI for XmlHttpRequest

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!

like image 998
Rushino Avatar asked Oct 04 '12 17:10

Rushino


People also ask

Does XMLHttpRequest support CORS?

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.

Should I enable CORS on my API?

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.

What is CORS in Web API with example?

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.


Video Answer


2 Answers

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 !

like image 50
Rushino Avatar answered Oct 09 '22 14:10

Rushino


Carlos Figueira has a nice series of posts about CORS and ASP.NET Web API:

  • Implementing CORS support in ASP.NET Web APIs
  • Implementing CORS support in ASP.NET Web APIs – Take 2
  • CORS support in ASP.NET Web API – RC version

Personally I'm a big fan of Take 2 approach because EnableCors attribute can be easly extended to give you control over allowed origins.

like image 32
tpeczek Avatar answered Oct 09 '22 15:10

tpeczek