简体   繁体   中英

Returning a custom message when 404 Not Found occurs in Web API

I have added config.Formatters.Remove(config.Formatters.XmlFormatter); to the Register method of WebApiConfig.cs in an ASP.NET Web API project. This works nicely to return JSON when a 404 Not Found exception occurs. I get a message like the following:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:2034/api/dfdf'.","MessageDetail":"No type was found that matches the controller named 'dfdf'."}

Is it possible to override this message to return a custom one? If so, how is it done? I'm using Web API 2.

It seems simple, but there are a bunch of places where ASP.Net automatically creates 404s (rather than your controller returning a 404 response manually).

  • No route matched.
  • Route is matched but no {controller} has been found on route.
  • No type with {controller} name has been found.
  • No matching action method found in the selected controller due to no action method start with the request HTTP method verb or no action method with IActionHttpMethodProviderRoute implemented attribute found or no method with {action} name found or no method with the matching {action} name found.

This article shows how to implement a custom IHttpControllerSelector and IHttpActionSelector that uses a typical ApiController to generate your custom 404 HttpResponseMessage .

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.

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