views:

4231

answers:

2

Hi folks,

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.

+9  A: 

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" }
    );
Pure.Krome
I've tried this, but it doesn't work. I have put the route under my default route, but i still get 404 errors.
Martijn
Hmm. i think it works for me.
Pure.Krome
Can you please explain what exactly I have to assuming I am very new to MVC.
Tanmoy
2 things. a) add that last route to your route list. b) create a controller (in my example, i called it StaticContentController) with an Action method (in my example, i added a method called PageNotFound(..)) add logic this method to display the 404 page not found, View.
Pure.Krome
If you still have the default route (I.E. {controller}/{action}/{id}) in RegisterRoutes() it will trap all URLs that match the format of a normal MVC request.In other words the catch-all route can only intercept a bad URL if it doesn't fit the normal format (**blah/blah/blah/blah**). In the case of a non-existent controller the exception must be handled through conventional ASP.NET handling.Theres a good description of handling at http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/620559#620559
RonnBlack
Indeed the 'catch all' is maybe not the best approach. Feedback on this answer pls: http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/2577095#2577095
cottsak
A: 

This might be a problem when you use

throw new HttpException(404);

When you want to catch that, I don't know any other way then editing your web config.

Paco
ActionFilters : use them to catch the HttpException.
Pure.Krome
What if the exception is not thrown by a controller action? I throw a 404 in my controller factory.
Paco
Not sure then - i'm not playing around with controller factories. soz.
Pure.Krome
Controllerfactory is not the only place where it can happen. I map a catch all route to an actionmethod that just throws the exception. The exception is handled by the web.config
Paco