繁体   English   中英

自定义“找不到与请求uri匹配的http资源”消息

[英]Customizing “No http resource was found that matches the request uri” message

是否有一种简单的方法来修改Web API返回的默认404消息?

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

您需要覆盖DelegatingHandler抽象类。

在此处查看更多内容来自ASP.Net Web API 2的统一,一致的错误响应

在这里, ASP.NET Web API异常处理

这样做的简单方法是“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()); //.... } } 

这就对了。 如果您需要更改任何其他错误消息,也是如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM