未找到预检请求404 .net Web api; 对预检请求的响应未通过访问控制检查:它没有http ok状态

O'D*_*ett 4 .net c# asp.net-web-api2

因此,我想在我的.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
Run Code Online (Sandbox Code Playgroud)

我已逐步按照Microsoft网站的概述进行操作,但仍然失败。

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: it does not have http ok status
Run Code Online (Sandbox Code Playgroud)

小智 5

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢这有效!Microsoft 网站上未记录此行 &lt;add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" module="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" /&gt; (2认同)
  • 太棒了,正在使用一些 SPA 元素对 .NET Framework 应用程序进行现代化改造,这救了我的命 (2认同)