Solved: "Access-Control-Allow-Origin" Error in WCF REST Service

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:

  1. <system.webServer>  
  2.       
  3.     <httpProtocol>  
  4.       <customHeaders>  
  5.         <add name="Access-Control-Allow-Origin" value="*" />  
  6.       </customHeaders>  
  7.     </httpProtocol>      
  8.       
  9.     <modules runAllManagedModulesForAllRequests="true"/>    
  10.     <directoryBrowse enabled="true"/>  
  11.   </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.

Up Next
    Ebook Download
    View all
    Learn
    View all