今天我們遇到了一個CORS跨域的問題
Ajax如下
var url = "http://localhost:11980/api/Demo/GetString"; //api地址
$.ajax({
type: "get",
url: url,
data: null,
headers:
{
SecretKey: "ec8b570ad4bd403783c52ecb5cdfa849",
AppKey: "1259402909",
UniqueKey: "987654321"
},
success: function (data) {
alert(data);
}
});
如果把 headers 去掉,CORS跨域是沒有問題的,但是加上就完犢子了
解決方案
Global 文件中添加一下代碼
protected void Application_BeginRequest(object sender, EventArgs e) { var res = HttpContext.Current.Response; var req = HttpContext.Current.Request; //自定義header時進行處理 if (req.HttpMethod == "OPTIONS") { res.AppendHeader("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name,Token,Cookie,SecretKey,UniqueKey,AppKey"); res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS"); res.AppendHeader("Access-Control-Allow-Origin", "*"); res.StatusCode = 200; res.End(); } }
Filters
public class ActionAuthFilters : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "*"); actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "*"); base.OnActionExecuted(actionExecutedContext); } }
Action
[ActionAuthFilters] [HttpGet] public string GetString() { return "OK"; }
解決問題
解釋為啥
因為 ajax 中添加了 headers
所以瀏覽器會發送兩次請求
第一次是OPTIONS 類型的請求,這個請求會詢問服務器支持哪些請求方法(GET,POST等),支持哪些請求頭等等服務器的支持情況。等到這個請求返回后,如果原來我們准備發送的請求符合服務器的規則,那么才會繼續發送第二個請求,否則會在Console中報錯。
第二次才是我們寫的那個 Get Post 請求
所以需要在 Application_BeginRequest 中判斷如果是OPTIONS 類型的請求 直接返回OK,並且告訴瀏覽器我們支持什么類型的請求,參數,URL
然后瀏覽器根據 Application_BeginRequest 中的配置在進行后續的操作
