Catch 404 errors in Asp.net Web API

2020-04-02 06:54发布

问题:

I am trying to catch 404 errors which are returned by the Asp.net Web API server.

However, Application_Error from inside Global.asax is not catching them.

Is there a way to handle these errors?

回答1:

You might want to take a look at Handling HTTP 404 Error in ASP.NET Web API which has a step by step example



回答2:

I know this is old, but I was also just looking for this, and found a very easy way that seems to work, so thought I'd add incase this can help someone else.

The solution I found, that works for me, is here. Also, this can be mixed with attribute routing (which I use).

So, in my (Owin) Startup class I just add something like..

public void Configuration(IAppBuilder app)
{      
     HttpConfiguration httpConfig = new HttpConfiguration();   
     //.. other config

     app.UseWebApi(httpConfig);

     //...
     // The I added this to the end as suggested in the linked post
     httpConfig.Routes.MapHttpRoute(
       name: "ResourceNotFound",
         routeTemplate: "{*uri}",
         defaults: new { controller = "Default", uri = RouteParameter.Optional });
    // ...

 }

  // Add the controller and any verbs we want to trap
  public class DefaultController : ApiController
  {
      public IHttpActionResult Get(string uri)
      {      
      return this.NotFound();
      }

      public HttpResponseMessage Post(string uri)
      {       
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotFound, "I am not found");
        return response;
      } 
   }    

Above you can then return any error object (in this example I am just returning a string "I am not found" for my POST.

I tried the xxyyzz (no named controller prefix) as suggested by @Catalin and this worked as well.