No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://www.yourdomain.com’ is therefore not allowed access.
Using a single domain
You may be tempted to solve this problem by moving the WCF service to your web application domain. By operating within the same domain, you will no longer receive the cross-domain error. However, this will tightly couple your web application and data service. If you need to access the service from a mobile app or another web application, you will run into the same problem. Centralizing your data store behind a common data service will allow for the maximum re-use across all of your applications which need to access the data.
Implementing Cross-Origin Resource Sharing (CORS)
In order to protect users while browsing the web, browsers will block AJAX requests to domains other than the originating HTML page. The CORS specification allows for applications to report to a browser if the cross-domain request can be allowed. By implementing CORS support in your WCF service, you can make your service application pass the required headers to allow for the AJAX requests from another domain to succeed.
The error message about the “Access-Control-Allow-Origin” header directly refers to these CORS headers. You can follow these simple steps to implement CORS on your RESTful WCF service.
The easy CORS fix
If you already have your WCF service up and running, as I had, the change to support GET requests is very minor. By making the following changes to the Web.config in your system.webServer section, you can get CORS headers up and running:
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*"/> <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" /> <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" /> <add name="Access-Control-Max-Age" value="1728000" /> </customHeaders> </httpProtocol>
This simple change will make your error go away.
NOTE! The Access-Control-Allow-Origin setting is set to a value of “*”. This will allow all callers to have access. This is great if your service is meant to be shared with anybody, including mobile apps, or if you are controlling access to your service via a firewall. However, if you want to make sure only your web application can access, you can change this value to “http://www.yourdomain.com”.
Some other good reads
In case you’re like me, you probably want to have a quick list of places to read up on the CORS WCF implementation:
- Cross-Domain Calls for a WCF Service
- Implementing CORS support in WCF
- RESTfull WCF Service with CORS and JQuery and Basic access authentication