【发布时间】:2015-07-22 04:43:36
【问题描述】:
有没有简单的方法可以修改Web API返回的默认404消息?
未找到与请求 uri 匹配的 http 资源
【问题讨论】:
标签: c# asp.net .net asp.net-web-api
有没有简单的方法可以修改Web API返回的默认404消息?
未找到与请求 uri 匹配的 http 资源
【问题讨论】:
标签: c# asp.net .net asp.net-web-api
【讨论】:
简单的方法是通过“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;
}
}
然后在web api注册配置文件中注册这个类
public static void Register(HttpConfiguration config){
public static void Register(HttpConfiguration config)
{
// you config and routes here
config.MessageHandlers.Add(new ApiGatewayHandler());
//....
}
}
就是这样。如果您需要更改任何其他错误消息,同样的方法。
【讨论】: