ASP.NET Web API 在使用 HttpPut 时不断返回 405“方法不允许”状态代码

本文关键字:方法 返回 不允许 方法不允许 代码 状态 API Web NET HttpPut ASP | 更新日期: 2023-09-27 17:57:03

在StackOverflow上,我看到很多人建议更改我的web.config,所以我将其更改为:

<modules>
  <remove name="FormsAuthentication" />
  <remove name="WebDAVModule" /> 
</modules>
<handlers> 
  <remove name="WebDAV" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%'Microsoft.NET'Framework'v4.0.30319'aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%'Microsoft.NET'Framework64'v4.0.30319'aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

然而,我仍然遇到与以前相同的问题。还有其他建议吗?我发布的方法只是一个简单的放置

var response = await client.PutAsJsonAsync($"api/{user.Email}/", user);

在 API 中,它调用的方法如下所示:

[HttpPut]
public void Account(string userName, JObject user)
{
    ....
}

这是路由配置

config.Routes.MapHttpRoute( 
    name: "IdentityApi", 
    routeTemplate: "{userName}/{action}/", 
    defaults: new { controller = "Identity", action = "Account" } 
);

ASP.NET Web API 在使用 HttpPut 时不断返回 405“方法不允许”状态代码

根据您的路由模板routeTemplate: "{userName}/{action}/"您调用了错误的 URL api/{user.Email}/

这里的假设是你的ApiController看起来像这样

public class IdentityController : ApiController {
    [HttpPut]
    public void Account(string userName, JObject user) { .... }
}

您应该更新路由模板以匹配所需的 URL

config.Routes.MapHttpRoute( 
    name: "IdentityApi", 
    routeTemplate: "api/{userName}", 
    defaults: new { controller = "Identity", action = "Account" } 
);

或您正在调用以匹配原始路由模板的 URL...

var response = await client.PutAsJsonAsync($"{user.Email}/", user);

你能在你的web.config中尝试这样吗:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />