ASP.NET Webapi same origin policy workaround using Custom Http Headers

Recently, I’m working on an API that should be accessed by both javascript and desktop clients. During debugging of the javascript client, I ran into the Same Origin Policy problem which prevented my javascript app to make XHR to the API. Both the client and the API are hosted on different ports which triggers this policy. localhost:35000 and localhost:35001

One such workaround is to have the API utilize Cross-Origin Resource Sharing. This is basically sending back the header <code>Access-Control-Allow-Origin: *</code> the asterisk(allow all domains) can be replaced with specific domain names. I utilized a custom http header attribute that can be used on the Controller or the Action;

Using it:

The headers should now look like:

Access-Control-Allow-Origin:* Cache-Control:no-cache Connection:Close Content-Type:application/json; charset=utf-8 Date:Sun, 29 Apr 2012 18:39:05 GMT Expires:-1 Pragma:no-cache Server:ASP.NET Development Server/ Transfer-Encoding:chunked X-AspNet-Version:4.0.30319

NOTE: This will work for GET requests. Any other method will fail, such as POST or PUT. The browser will send a pre-flight request which contains the method OPTIONS, which would not be mapped to the action and the ASP.NET routing engine will just return an error. If you need CORS support for all methods, use a DelegatingHandler, explained here: