For security reasons, browsers restrict cross-origin HTTP
requests initiated from within scripts.
For example, XMLHttpRequest follows the same-origin policy. So, a web application
using XMLHttpRequest could only make HTTP requests to its own domain unless
CORS headers are added in the response.
Given below is the code to add CORS header to response in
asp.net
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "domain.com" );
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
If you want to include CORS header for requests from all
domains, you have to format the referrer url to get the correct domain
public static string GetDomain(string referrer)
{
string tmpReferrer = String.IsNullOrEmpty(referrer)
|| referrer.Length < 5 ? "" : referrer;
// strip out the domain portion of the referring url, if
there is a starting point
if (tmpReferrer.Length > 0
&& tmpReferrer.Substring(0, 4) == "http")
{
//remove string after first /
if (tmpReferrer.IndexOf("/",
8) > 0)
{
tmpReferrer = tmpReferrer.Substring(0, tmpReferrer.IndexOf("/",
8));
}
//remove string after first ?
if (tmpReferrer.IndexOf("?")
> 0)
{
tmpReferrer = tmpReferrer.Substring(0, tmpReferrer.IndexOf("?"));
}
}
else if (tmpReferrer.Length > 0)
{
//remove string after first /
if (tmpReferrer.IndexOf("/")
> 0)
{
tmpReferrer = tmpReferrer.Substring(0, tmpReferrer.IndexOf("/",
8));
}
}
return tmpReferrer;
}
And then call the function to add domain name to CORS header
string referrer = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", GetDomain(referrer));
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
JS code to call endpoint
var httpRequest = new XMLHttpRequest();
httpRequest.open("GET", "http://somedomain.com/endpoint", true);
httpRequest.withCredentials = true;
httpRequest.send();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState ==
4) {//wait for request to complete
console.log(httpRequest.responseText);
}
};