18

I want to be able to capture the exception that is thrown when a user requests a non-existent controller and re-direct it to a 404 page. How can I do this?

For example, the user requests http://www.nosite.com/paeges/1 (should be /pages/). How do I make it so they get re-directed to the 404 rather than the exception screen?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
jmcd
  • 4,269
  • 5
  • 36
  • 36

3 Answers3

16

Just use a route:

// We couldn't find a route to handle the request.  Show the 404 page.
routes.MapRoute("Error", "{*url}",
    new { controller = "Error", action = "404" }
);

Since this will be a global handler, put it all the way at the bottom under the Default route.

Dale Ragan
  • 18,202
  • 3
  • 54
  • 70
  • 6
    Is this right? Because sure if I define a route for {controller}/{action}/{id} lets say, and the user enters the url with a controller that doesn't exist then it will yellow-screen as that first route will match and your catch all will never be reached? – jmcd Oct 22 '08 at 19:48
  • I just tried this, and still get the default yellow-screen 404. – Josh Simerman Dec 15 '11 at 21:03
  • 1
    This does work, but it means that you have to have manual routes for all of your controllers, ie no `{controller}/{action}/{id}` instead you'd have to do `Home/{action}/{id}`, `Account/{action}/{id}`, etc – Serj Sagan Jan 22 '13 at 23:01
  • @SerjSagan, nowadays, you can use route constraints, like: `routes.MapRoute( name: "Home", url: "{action}", defaults: new { controller = "Home", action = "Index" }, constraints: new { action = "Index|Help|Orders" } );` – R. Schreurs Mar 08 '16 at 12:43
6

Take a look at this page for routing your 404-errors to a specified page.

Espo
  • 41,399
  • 21
  • 132
  • 159
1

Found this on the same site - Strategies for Resource based 404s

jmcd
  • 4,269
  • 5
  • 36
  • 36