2017-12-18 142 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()); 

您可以檢查響應的狀態代碼和生成自定義基於它的錯誤消息。