Recently I was working on a JSON based WCF REST Service. It was a simple service performing CRUD operations. When I tried to consume the service from a web-based client I got the following errors in the browser console.
The error message was "No Access-Control-Allow-Origin header is present on the required resource". The service was running on a different server and it was not configured to accept a request from any origin. This error can be resolved by enabling CORS: Cross Origin Resource Sharing for the service.
You can enable CORS on a service hosted on IIS or IIS Express by adding the following configuration in the config file.
We have added a custom header that sets the Access-Control-Allow-Origin value to *. By setting it to *, we are allowing requests from any origin to access the service. So to solve the error I went ahead and added the following configuration in the web.config of service under the system.webServer section:
- <system.webServer>
-
- <httpProtocol>
- <customHeaders>
- <add name="Access-Control-Allow-Origin" value="*" />
- </customHeaders>
- </httpProtocol>
-
- <modules runAllManagedModulesForAllRequests="true"/>
- <directoryBrowse enabled="true"/>
- </system.webServer>
After adding the preceding configuration you should be able to access a service in client side code like JavaScript. I hope this article is useful.