【问题标题】:Customizing "No http resource was found that matches the request uri" message自定义“未找到与请求 uri 匹配的 http 资源”消息
【发布时间】:2015-07-22 04:43:36
【问题描述】:

有没有简单的方法可以修改Web API返回的默认404消息?

未找到与请求 uri 匹配的 http 资源

【问题讨论】:

    标签: c# asp.net .net asp.net-web-api


    【解决方案1】:

    【讨论】:

    • 而不是像链接 #2 中的更新建议那样使用 OWIN 中间件?
    • 当然可以使用 OWIN 中间件。我的建议是两种都试一下,看看哪一种更适合你
    【解决方案2】:

    简单的方法是通过“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. 然后在web api注册配置文件中注册这个类

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

    就是这样。如果您需要更改任何其他错误消息,同样的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2016-12-01
      • 2016-01-26
      相关资源
      最近更新 更多