Friday, May 31, 2013

Fixing CORS issue in Web API: "Origin is not allowed by Access-Control-Allow-Origin"

For security reasons browsers prohibit AJAX calls to Web API service outside the existing site. This means you can't provide a service exposed by Web API to a site on another domain. This is called Cross Origin Resource Sharing (CORS).

This problem should be resolved in .NET Framework 5 and I've found several articles on how to incorporate "Nightly ASP.NET Build" feature into your existing Web API service.  I'm not really comfortable with that and it can be hard to get it working properly. 

All you have to do to fix this issue is add a few lines to your web.config under the system.webServer:

   1:  <system.webServer>
   2:     <httpProtocol>
   3:        <customHeaders>
   4:           <add name="Access-Control-Allow-Origin" value="*"/>
   5:        </customHeaders>
   6:     </httpProtocol>
   7:  <system.webServer>