Is there a simple way to modify the default 404 message returned by Web API?
No http resource was found that matches the request uri
You need to override the DelegatingHandler abstract class.
see more here Uniform, consistent error responses from ASP.Net Web API 2
and here, ASP.NET Web API Exception Handling
The simple way to do that is by "DelegatingHandler"
First Step is to create a new class inherits from 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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.