13

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?

3
  • What goal you want to achieve by this? Commented Nov 20, 2013 at 14:48
  • I am trying to return a friendly error message to the user instead of returning the IIS HTML page. (The project is made to be requested only using API calls with JSON or XML responses) Commented Nov 20, 2013 at 14:55
  • Do you have full control over the ApiControllers' code? Commented Nov 20, 2013 at 15:03

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the awesome link. I was looking for something like this just yesterday for my Web API Project and somehow it didn't show up on my search results.
That is a good link, thank you. Unfortunately, it won't catch all the 404 errors. For example, typing localhost:34123/xxyyzz doesn't gets caught.
unfortuntely I couldn't make this work because of using attribute routing.
2

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.

1 Comment

Great Solution! This helped me with mine. However, I am unsure when I do Get and Post, it doesn't work. I must put [HttpGet] on function Get and [HttpPost] on function Post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.