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?

3 Answers 3

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.

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

4 Comments

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?
I just tried this, and still get the default yellow-screen 404.
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
@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" } );
6

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

1 Comment

You might want to update the answer to include relevant details in it.
1

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

1 Comment

Link only answers are discouraged on SO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.