[英]Customizing “No http resource was found that matches the request uri” message
Is there a simple way to modify the default 404 message returned by Web API? 是否有一种简单的方法来修改Web API返回的默认404消息?
No http resource was found that matches the request uri
找不到与请求uri匹配的http资源
You need to override the DelegatingHandler abstract class. 您需要覆盖DelegatingHandler抽象类。
see more here Uniform, consistent error responses from ASP.Net Web API 2 在此处查看更多内容来自ASP.Net Web API 2的统一,一致的错误响应
and here, ASP.NET Web API Exception Handling 在这里, ASP.NET Web API异常处理
The simple way to do that is by "DelegatingHandler" 这样做的简单方法是“DelegatingHandler”
First Step is to create a new class inherits from DelegatingHandler: 第一步是创建一个继承自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; }
} }
Then Register this class in the web api Register config file 然后在web api注册配置文件中注册此类
public static void Register(HttpConfiguration config){ public static void Register(HttpConfiguration config) { // you config and routes here config.MessageHandlers.Add(new ApiGatewayHandler()); //.... } }
That is it. 这就对了。 Same way if you need to change any other error message.
如果您需要更改任何其他错误消息,也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.