2015-07-22 101 views

回答

1

簡單的方式做到這一點是 「DelegatingHandler」

  1. 第一步是創建一個新的類從DelegatingHandler繼承:

    public class ApiGatewayHandler : DelegatingHandler 
        { 
         protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
         { 
         var response = await base.SendAsync(request, cancellationToken); 
    
         if (response!=null && response.StatusCode == HttpStatusCode.NotFound) 
         { 
          var msg = await response.Content.ReadAsStringAsync(); 
    
          //you can change the response here 
          if (msg != null && msg.Contains("No HTTP resource was found")) 
          { 
           return new HttpResponseMessage 
           { 
            StatusCode = HttpStatusCode.NotFound, 
            Content = new ObjectContent(typeof(object), new { Message = "New Message..No HTTP resource was found that matches the request URI" }, new JsonMediaTypeFormatter()) 
           }; 
          } 
         } 
         return response; 
    
        return response; 
    } 
    

    }

  2. 然後在網頁API註冊的配置文件

    public static void Register(HttpConfiguration config){ 
        public static void Register(HttpConfiguration config) 
        { 
         // you config and routes here     
    
         config.MessageHandlers.Add(new ApiGatewayHandler()); 
    
         //.... 
        } 
    } 
    

這就是它註冊這個類。同樣的方法,如果你需要改變任何其他錯誤信息。

相關問題