How to make a catch all route to handle '404 page not found' queries for ASP.NET MVC?

Pure.Krome picture Pure.Krome · Nov 22, 2008 · Viewed 92.3k times · Source

Is it possible to create a final route that catches all .. and bounces the user to a 404 view in ASP.NET MVC?

NOTE: I don't want to set this up in my IIS settings.

Answer

Pure.Krome picture Pure.Krome · Nov 22, 2008

Found the answer myself.

Richard Dingwall has an excellent post going through various strategies. I particularly like the FilterAttribute solution. I'm not a fan of throwing exceptions around willy nilly, so i'll see if i can improve on that :)

For the global.asax, just add this code as your last route to register:

routes.MapRoute(
    "404-PageNotFound",
    "{*url}",
    new { controller = "StaticContent", action = "PageNotFound" }
    );