一、基础解决方案(基础配置)
通过Ajax调用web api路径时报错:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
C#自带的web api并不能支持跨域访问,如果需要,可以更改配置来实现。
1、更改Web.config文件,加上如下代码
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type,Token" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
2、然后需要配置Global.asax文件
插入如下代码:
/// <summary>
/// 配置Ajax跨域访问
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.HttpMethod.ToUpper() == "OPTIONS")
{
Response.StatusCode = 200;
Response.End();
}
}
配置这两个文件之后,web api就可以跨域访问了。
二、跨域产生异常的解决方案
1、webapi处理OPTIONS请求 报错1信息
Access to XMLHttpRequest at 'https://localhost:4445/api/v/getmsg' from origin 'https://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
解决方案:把value值改成特定的域名
<system.webserver>
<httpprotocol>
<customheaders>
"Access-Control-Allow-Origin" value="https://localhost:8083" />
</customheaders>
</httpprotocol>
</system.webserver>
2、Access to XMLHttpRequest at 'https://localhost:4445/api/v/getmsg' from origin 'https://localhost:9528' 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.
配置行继续添加
<"Access-Control-Allow-Credentials" value="true" />
3、It does not have HTTP ok status Ajax请求一般会做options状态监测,需要返回200
Access to XMLHttpRequest at 'https://localhost:4445/api/v/getmsg' from origin 'https://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Global.asax 中添加
/// <summary>
/// 配置Ajax跨域访问
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.HttpMethod.ToUpper() == "OPTIONS")
{
Response.StatusCode = 200;
Response.End();
}
}
来源:CSDN
作者:鱼头玻璃心
链接:https://blog.csdn.net/huazaizuiaiw/article/details/104147288