asp.net - 405 方法选项不允许在 asp.net web api Controller 中使用?

标签 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对于所有原始 header 和方法,这也不起作用。

最佳答案

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

关于asp.net - 405 方法选项不允许在 asp.net web api Controller 中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43459226/

相关文章:

javascript - 如何使用 javascript 访问 View 状态?

javascript 无法设置属性 selectindex 列表框

asp.net-mvc - 为什么 MVC 4 bundle 不捆绑 Knockout.js?

c# - 更改参数名称 Web Api 模型绑定(bind)

c# - 为什么我的 ClaimsIdentity IsAuthenticated 总是错误的(对于 web api 授权过滤器)?

c# - ASP.NET 母版页错误

vb.net - 单击电子邮件中的链接时如何避免启动浏览器

asp.net-mvc-4 - 没有参数的 MVC4 ActionLink 指向当前路径

c# - COMException CreateInstance 发布失败

c# - MVC 4 Web Api Controller 没有默认构造函数?