asp.net web api控制器中不允许405个方法选项?

时间:2017-04-17 20:40:19

标签: asp.net asp.net-mvc-4 asp.net-web-api cors

我有这个非常常见的问题,它说明OPTIONS请求的方法不允许(GET)。每当我进行API调用时,我都会收到以下错误。我在web.config

中有此设置
<system.webServer>
  <modules>
    <remove name="WebDAVModule"/>
  </modules>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*"/>
      <add name="Access-Control-Allow-Headers" value="Origin, Authorization, X-Requested-With, Content-Type, Accept"/>
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
    </customHeaders>
  </httpProtocol>
  <handlers>
    <remove name="WebDAV"/>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
    <remove name="OPTIONSVerbHandler"/>
    <remove name="TRACEVerbHandler"/>
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
  </handlers>
</system.webServer>

我尝试使用Asp.Net.WebApi.Cors并使用EnableCors()对所有原始标头和方法全局强制执行CORS,但这也不起作用。

1 个答案:

答案 0 :(得分:10)

handlers <remove name="OPTIONSVerbHandler"/>之后,添加以下内容:

<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS"
  modules="IsapiModule" requireAccess="None"
  scriptProcessor="C:\Windows\System32\inetsrv\asp.dll"
  resourceType="Unspecified" />

请参阅IIS hijacks CORS Preflight OPTIONS request上的答案。

或者甚至可能就是这样:

 <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS"
   modules="ProtocolSupportModule" requireAccess="None" />

如果这不起作用,则会在global.asax或其他代码中添加以下内容:

protected void Application_BeginRequest(object sender,EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
        HttpContext.Current.Response.End();
    }
}