c# - PreFlight Request 404 not found .net web api;对预检请求的响应未通过访问控制检查:它没有 http ok 状态
问题描述
所以我想在我的 .net Web API 上启用 CORS,但客户端应用程序不断收到 404 选项请求和第二个错误:
Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: it does not have http ok status
我一步一步地按照微软网站的大纲进行了操作,但仍然没有成功。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Added this line to my WebApiConfig.cs file
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
I also tried it by adding the headers in the Web.config in the httpProtocol tag file like so:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
</customHeaders>
</httpProtocol>
解决方案
Try to enable from the web.config file under <system.webserver></system.webserver> like so:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
</customHeaders>
</httpProtocol>
To handle the preflight request error add the line below in the <handlers></handlers> tags:
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" />
Then in the Global.asax file, add the following method:
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.Flush();
}
}
推荐阅读
- java - JsonTypeInfo.As.WRAPPER_OBJECT 是否有任何 swagger.json 标记?
- python - ModuleNotFoundError:没有名为“推理”的模块
- typescript - 静态工厂方法与构造函数
- php - app($classModel)->getQuery() != app($classModel)->query() 或 app($classModel)->getQuery() != $classModel::query()
- r - 找不到源目录,希望在 /opt/build/repo/content 中找到它
- google-sheets - 根据多个条件返回一列的总和,SUMIFS 用法?
- c - 免费的`mmap()-ed`私有大页面
- firebase - 错误类型错误:无法读取未定义 angular6 的属性“推送”
- node.js - 在 iframe 中加载的应用程序如何相互发送消息
- android - 无法在前面的同级 xpath 上模拟单击操作