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?
A simple solution is to check for the HTTP status code 404 in the response. If found, you can redirect the control to a page that exists. The following code snippet illustrates how you can write the necessary code in the Configure method of the Startup class to redirect to the home page if a 404 error has occurred.
You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception.
Return InternalServerError for Handled Exceptionscs file and locate the Get(int id) method. Add the same three lines within a try... catch block, as shown in Listing 2, to simulate an error. Create two catch blocks: one to handle a DivideByZeroException and one to handle a generic Exception object.
You might want to take a look at Handling HTTP 404 Error in ASP.NET Web API which has a step by step example
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With