CORS跨域原理:
CORSajax请求设置ORigin
服务器通过设置Access-Control-Allow-Origin来进行,如果浏览器检测到相对应的设置,就可以允许ajax进行跨域的访问。
客户端:
var xhr = new XMLHttpRequest();
xhr.open("post", "http://b.example.com/Test.ashx", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 声明请求源
xhr.setRequestHeader("Origin", "http://a.example.com");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var responseText = xhr.responseText;
console.info(responseText);
}
}
xhr.send();
}
服务器端:
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
// 声明接受所有域的请求
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}