Web Api - 不允许捕获 405 方法 [英] Web Api - Catch 405 Method Not Allowed
问题描述
截至目前,Web api 应用程序为 405 - Method Not Allowed 错误返回以下响应正文.我正在尝试更改响应正文,但我不知道如何使用委托处理程序、ApiControllerActionSelector 或过滤器.任何人都可以帮助我捕获服务器端的 405 错误吗?
As of now, the Web api application returns the below response body for 405 - Method Not Allowed error. I am trying to change the response body, but I don't know how the delegating handler, ApiControllerActionSelector or filter can be used. Can anyone help me on catching the 405 error in server side?
<代码>{消息:请求的资源不支持 http 方法‘GET’."}
注意:我的 api 控制器有 [RoutePrefix] 值.
Note: My api controllers has [RoutePrefix] value.
推荐答案
您可以使用 DelegatingHandler 来捕获传出的响应并像这样覆盖其行为.
You could use a DelegatingHandler to catch the outgoing response and override its behaviour like this.
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...
In Global.asax...
config.MessageHandlers.Add(new MethodNotAllowedDelegatingHandler());
这篇关于Web Api - 不允许捕获 405 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!