Web.Config
<system.webServer> <!--跨域设置--> <httpProtocol> <customHeaders> <remove name="Access-Control-Allow-Origin" /> <remove name="Access-Control-Allow-Headers" /> <remove name="Access-Control-Allow-Methods" /> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="*" /> <add name="Access-Control-Allow-Methods" value="*" />--> <add name="Access-Control-Allow-Credentials" value="true" /> </customHeaders> </httpProtocol> </system.webServer>
Global.asax
/// <summary> /// /// </summary> protected void Application_BeginRequest(object sender, EventArgs e) { // 允许所有的options请求,直接返回200状态码 if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.StatusCode = 200; //HttpContext.Current.Response.Headers["Access-Control-Allow-Origin"] = HttpContext.Current.Request.Headers["origin"]; HttpContext.Current.Response.End(); return; } }
PS:
1.Error: 需要设置(Access-Control-Allow-Credentials = true)
xxx Access to XMLHttpRequest at 'https://xxx' from origin 'https://xxx' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
2.Error: 多个Access-Control-Allow-Origin,重复配置
Access to XMLHttpRequest at 'https://xxx' from origin 'https://xxx' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'https://xxx, https://xxx', but only one is allowed.
3.浏览器会拒绝任何不带 Access-Control-Allow-Credentials
: true
标头的响应,且不会把响应提供给调用的网页内容
4.附带身份凭证的请求时,不支持通配符