2017-12-18 98 views
0

我正试图处理405Method not Allowed)从WebApi产生的错误。处理405错误

例如:基本上这个错误将被处理,只要有人用Post请求而不是Get来调用我的Api。

我想以编程方式进行此操作(即没有IIS配置),现在没有处理这种错误的文档,并且在发生此异常时不会触发IExceptionHandler

任何想法?

+0

网络服务器是Windows服务器上的IIS吗? – creyD

+0

是的,但我无法控制服务器或IIS,因此如果有方法可以通过编程方式处理它,那将会更好。 – Ayman

回答

1

部分响应: 通过查看here中的HTTP消息生命周期,可以在HttpRoutingDispatcher之前的管道的早期添加消息处理程序。

因此,创建一个处理程序类:

public class NotAllowedMessageHandler : DelegatingHandler 
{ 
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     var response = await base.SendAsync(request, cancellationToken); 

     if (!response.IsSuccessStatusCode) 
     { 
      switch (response.StatusCode) 
      { 
       case HttpStatusCode.MethodNotAllowed: 
       { 
        return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed) 
        { 
         Content = new StringContent("Custom Error Message") 
        }; 
       } 
      } 
     } 

     return response; 
    } 
} 

在你WebApiConfig,注册方法中添加以下行:

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

您可以检查响应的状态代码和生成自定义基于它的错误消息。