首页 > 解决方案 > 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>
    

标签: c#.netasp.net-web-api2

解决方案


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();
  }
}


推荐阅读