前端
$.ajax({
type: 'post',
crossDomain: true,
url: 'http://localhost:10771/RMBase/API/APIHandler.ashx',
data:{ "UserName": "aabbc","Pwd":"123" },
contentType: "application/json", // POST时必须
xhrFields: {
'Access-Control-Allow-Origin': '*'
},
success: function (data, textStatus, jqXHR) {
alert(data);
alert(jqXHR.getAllResponseHeaders());
//console.log("getAllResponseHeaders:" + jqXHR.getAllResponseHeaders());
// console.dir(jqXHR);
// Backbone.history.navigate("#booklist", true);
}
});
C# 端
一、放在Global.asax 中
protected void Application_BeginRequest()
{
// 允许跨域访问的源,生产环境建议替换为具体域名
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-Requested-With");
// 处理预检请求
if ("OPTIONS" == HttpContext.Current..Request.RequestType)
{
context.Response.StatusCode = 204;
context.Response.End();
}
}
}
二、每次请求是设置Header
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-Requested-With");
if ("OPTIONS" == context.Request.RequestType)
{
context.Response.StatusCode = 204;
context.Response.End();
}
else
{
using (var reader = new StreamReader(context.Request.InputStream))
{
string json = reader.ReadToEnd();
}
context.Response.Write("Hello World");
}
}