405方法选项在ASP.NET Web API控制器中不被允许? [英] 405 method options not allowed in asp.net web api controller?

查看:158
本文介绍了405方法选项在ASP.NET Web API控制器中不被允许?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常常见的问题,它说GET请求不允许使用方法(OPTIONS).每当我进行API调用时,都会收到以下错误消息.我在web.config中有此设置:

I have this very common issue where it says method not allowed (OPTIONS) for a GET request. I am getting the following error whenever I make an API call. I have this setting in 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,但这都不起作用.

I tried using Asp.Net.WebApi.Cors and enforcing CORS globally using EnableCors() for all origin headers and methods and that did not work either.

推荐答案

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

In your handlers after <remove name="OPTIONSVerbHandler"/>, add this:

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

请参见 IIS劫持CORS飞行前选项请求.

也许甚至是这样:

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

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

If that doesn’t work, something that will is adding the following in your global.asax or other code:

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

这篇关于405方法选项在ASP.NET Web API控制器中不被允许?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆