Cross Domain AJAX Request

In my earlier blogs, I have explored ASP.Net and JQuery topics. You may also read - How to Call ASP.Net web method using JQuery Ajax
In this blog let's see about Cross Domain AJAX Request.
Sometimes you have noticed that the browser refuses access to remote resources which you have requested. Do you know the reason behind it?
The reason behind this is that you try to request a cross-domain request from JQuery, the request could be an external file, library or AJAX call.

Because of this request for an external resource is not complete and you are not able to fetch data. This could be due to Cross-Origin Resource Sharing (CORS) policy.

Cross-Origin Resource Sharing (CORS)

Generally, there is a rule that how a webpage can access an external resource for eg fonts, stylesheet, jquery library, AJAX requests. Under the same-origin policy, a web browser does not allow access to a resource which is different from the current origin, a difference could be port, hostname etc.

This limitation can be resolve by Cross-Origin Resource Sharing (CORS). CORS defines a process where a web browser and web server communicate and determine whether to allow a web page to access a resource which is from a different origin.

When you make a cross-origin request the browser sends origin header with a value which contains a domain name. You can add an origin header in web.config like this.
This will allow all domain for a cross-origin request.

<add name="Access-Control-Allow-Origin" value="*" />

Below line will allow cross-origin requests only from a domain called sharepointcafe.net

<add name="Access-Control-Allow-Origin" value="www.sharepointcafe.net" />

Sometimes you may notice below error message in the console of the browser:
Error - Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. This error is because in origin header domain name is not allowed for which you are accessing a resource.


Comments

Popular