简体   繁体   中英

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?

No http resource was found that matches the request uri

The simple way to do that is by "DelegatingHandler"

  1. 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; } 

    }

  2. 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.

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