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

时间:2016-07-15 13:18:44

标签: c# asp.net asp.net-web-api asp.net-web-api-routing

在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" } 
);

2 个答案:

答案 0 :(得分:0)

根据您的路线模板routeTemplate: "{userName}/{action}/",您拨打了错误的网址api/{user.Email}/

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

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

您应该更新路线模板以匹配您想要的网址

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

或您调用的URL与原始的routeTemplate匹配...

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

答案 1 :(得分:0)

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

class GeneralController < ApplicationController
    before_action :renew_google_token, only: [:home]

    def renew_google_token
        # Get first Identity that will soon expire. This will be repeated unti lall identities are updated
        current_user.identities.where(provider: :google).where("expires_at < (?)", Time.now + 7.days).each do |identity|
            # Logic that pings Google and renews the token
            new_token_hash = something
            identity.update(token: new_token_hash.token, expires_at: Time.at(new_token_hash.expires_at))
        end
    end
end