CORS跨域 Ajax headers 问题
发布时间:2020-12-16 03:02:31 所属栏目:百科 来源:网络整理
导读:今天我们遇到了一个CORS跨域的问题 Ajax如下 var url = "http://localhost:11980/api/Demo/GetString"; //api地址$.ajax({ type: "get",url: url,data: null,headers: { SecretKey: "ec8b570ad4bd403783c52ecb5cdfa849",AppKey: "1259402909",UniqueKey: "98
今天我们遇到了一个CORS跨域的问题 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); } });
解决方案 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(); } }
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); } }
[ActionAuthFilters] [HttpGet] public string GetString() { return "OK"; } 解决问题 解释为啥 所以需要在 Application_BeginRequest 中判断如果是OPTIONS 类型的请求 直接返回OK,并且告诉浏览器我们支持什么类型的请求,参数,URL然后浏览器根据 Application_BeginRequest 中的配置在进行后续的操作 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |