HTML5 and Cross-Origin Resource Sharing call
Thursday 17 November 2011
A technique that has been used for quite some time to solve this problem is JSONP. Basically when you are doing a JSONP style call the request is done by adding a DOM element to the page instead of using the XMLHttpRequest object. While JSONP works it has a number of drawbacks in that you can only do a HTTP GET and if there is an error you will not get any feedback, instead you simply never get a response.
The new HTML 5 Cross-Origin Resource Sharing, aka as CORS, fixes this problem by allowing our code to call into services on other domains with full security still being enforced by the browser.
To demo CORS I am using two real simple ASP.NET MVC applications. One of these contains a simple JSON action method and both sites call this same controller action method to retrieve the JSON and display it.
If I open both sites in the browser and try to run the code I get these results. The image on the left is the page on the same side as the service and the image on the right shows the results of the cross domain call.
Its clear that the cross domain request didn’t work as it came back with an error status
So with a minimal change to the service this works just fine.
You can get far more control though. There are a number of other HTTP headers, both on the request and response, you can use to fine tune the behavior of CORS. More complex scenarios actually result in multiple calls being made behind the scenes, first a preflight request is made to check for the required permissions and only when that is satisfied the actual request is made.
All together CORS is a real nice feature to have. As usual the only problem is that Internet Explorer, even IE 10, doesn’t support it Check CanIUse.com for support details.