Return custom message when 404 Not Found occurs in Web API

I added config.Formatters.Remove(config.Formatters.XmlFormatter);to the method Registerfor WebApiConfig.cs in the ASP.NET Web API project. This works great to return JSON when a 404 Not Found exception is thrown. 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 this done? I am using Web API 2.

+4
source share
1 answer

It seems simple, but there are many places where ASP.Net automatically creates 404s (instead of having your controller return a 404 response manually).

  • Route not agreed.
  • Route agreed, but {controller} not found on route.
  • {controller}.
  • - HTTP- IActionHttpMethodProviderRoute, {action} name no method with the matching {action } .

, IHttpControllerSelector IHttpActionSelector, ApiController 404 HttpResponseMessage.

+3

Source: https://habr.com/ru/post/1532023/


All Articles