WCF Service with Cross Domain Support

When we try to make an AJAX call to a web service that is hosted on a different domain, we get an Access Denied exception on the client side JavaScript. This error is due to the Same Origin Policy that the browsers implement to prevent Cross-Domain requests (XDRs).

To address this problem with a WCF service, we can add the following settings to the Web.config file:

<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="PUT, GET, POST, DELETE, OPTIONS" />

These settings enable the web service to add custom headers on the response to allow requests from any or specific domains. It also allows the service to enable specific headers and web methods.

Setting Name
Allow requests from All domains when using * or use a comma delimited string with a list of domains.
Allow requests to send a list of headers on the request.
Allow HTTP methods. If you want to allow only GET requests, the value should contain only that method

After updating the configuration settings, we can try the XDR call again, and we should be able to get the response from the web service. 

Preflight Request:

The browsers sends an OPTION requests to the server to verify the Access-Control-Request-Method. If the server, has the method configured (PUT,POST,DELETE and OPTIONS), the server responds with a 200 indicating that is is allowed. if it is allowed, the server sends the real request (POST etc). Otherwise, the Access Denied exception is thrown.

JavaScript XDR Call notes:

One IE8 and more recent version, there is the XDomainRequest object. This object should be used for XDR calls instead of the XMLHttpRequest object. On other browsers, this functionality is already available when using XMLHttpRequest. If you are using a JavaScript framework like JQuery, you should read the specifications in how to handle the XDR calls when using IE8+. For the other browsers, the support should already be enabled since JQuery uses the XMLHttpRequest object.

I hope this tip helps you overcome this issue.