Saturday, 2 March 2013

Calling cross domain without Jsonp

Thanks to Simon Cropp @simoncropp (creator of NotifyPropertyWeaver project amongst other great projects) for pointing out that you shouldn’t need to jump through the hoops of using Jsonp.

http://enable-cors.org

http://www.html5rocks.com/en/tutorials/cors/

http://stevenhollidge.com/blog-source-code/cors   (using Javascript XMLHttpRequest rather than jQuery)

My example was taken from html5rocks website, then stripped back to contain only the cors code

Use this page to test CORS requests:  http://client.cors-api.appspot.com/client

Initially, I had been using jQuery to make my requests but their lack of support for cors with IE had led me down the wrong path:  http://bugs.jquery.com/ticket/8283

To enable CORS on your ASP.NET web server, for example for Web API, you need to add the following to your web.config:

<system.webServer>

<!-- enable cors -->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>

1 comment:

  1. thanks it works! :)
    Allow external origin requests IMHO it is dangerous and it's need to implement an authentication system. :D But for intranet applications is great!
    bye! :)

    ReplyDelete