Sunday, September 8, 2013

CORS support for ASP.NET Web API


CORS (Cross-Origin Resource Sharing) in an ASP.NET Web API 


I have been facing a dreadful issue "access denied access-control-allow-origin not included in response" error whenever I tried to send an AJAX request. I was able to land my call to the web API service and also checked that the Web API service was returning the correct response with correct headers. Still I was unable to find the solution to it and it really got frustrating.

I followed several tutorials on the web to allow the CORS in web API like:

http://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API

then I found this one

http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx

This tutorial here was the most comprehensive one and actually contained everything that we should know about CORS and moved me one step ahead. I was successfully able to send CORS requests on my local machine.

Again this error appeared when I deployed in production and then I had to remove the previous CORS handler. I was back to square one and was really desperate to find a solution because this was happening in production.

Finally, I found the magical lines which did the trick for me. Thanks to http://encosia.com/using-cors-to-access-asp-net-services-across-domains/ article.

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


I hope it helps someone in need because I definitely know how miserable our life gets if such an issue appears.

No comments:

Post a Comment