Web Api - 不允许使用 Catch 405 方法

Posted

技术标签:

【中文标题】Web Api - 不允许使用 Catch 405 方法【英文标题】:Web Api - Catch 405 Method Not Allowed 【发布时间】:2014-08-21 08:29:57 【问题描述】:

截至目前,Web api 应用程序返回以下响应正文 405 - Method Not Allowed 错误。我正在尝试更改响应正文,但我不知道如何使用委托处理程序、ApiControllerActionSelector 或过滤器。谁能帮我解决服务器端的 405 错误?

message: "The requested resource does not support http method 'GET'."

注意:我的 api 控制器具有 [RoutePrefix] 值。

【问题讨论】:

【参考方案1】:

您可以使用DelegatingHandler 来捕获传出响应并像这样覆盖其行为。

public class MethodNotAllowedDelegatingHandler : DelegatingHandler

    async protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
    
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
        if (response.StatusCode == HttpStatusCode.MethodNotAllowed)
        
            // adjust your response here as needed...
        
        return response;
    

在 Global.asax...

config.MessageHandlers.Add(new MethodNotAllowedDelegatingHandler());

【讨论】:

以上是关于Web Api - 不允许使用 Catch 405 方法的主要内容,如果未能解决你的问题,请参考以下文章