2015-07-22 58 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()); 
    
         //.... 
        } 
    } 
    

这就是它注册这个类。同样的方法,如果你需要改变任何其他错误信息。

相关问题