0 Comments

In a WebAPI application, by default when you hit an endpoint that does not exists you get a 404 response (with htnl in the body no less…..even if you are doing it from a webapi endpoint), and all of that is done through the framework and the routing mechanism. A quick and easy way to have control over this, is by adding a controller with a route that will be acting as a catch all. For the controller it goes like so:

public class DefaultController : ApiController
{
    public IHttpActionResult Get(string uri)
    {
        // do what is needed
        return this.NotFound();
    }
}

and the route would look like this:

config.Routes.MapHttpRoute(
    name: "ResourceNotFound",
    routeTemplate: "api/{*uri}",
    defaults: new { controller = "Default", uri = RouteParameter.Optional });

by adding this route any GET that is not mapped will default this this controller, what makes it work is the {*uri}, this capture everything that is after the api/, so in your controller you have access to the URI that was requested. This is an easy and quick way if you wanted to create a better response with a message stating what was the requested URI or needed to create some stats based on those unmatched route.

Things to note:

  • DO NOT put this route as a RouteAttribute (in WebAPI 2) if your routes are defined as RouteAttribute, because you’ll get an error:
Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL
  • This route should be the LAST route in your route collection and if lucky your only route defined that way.

 

Happy coding