views:

6042

answers:

4

I am trying to make a custom HTTP 404 error page when someone types in a URL that doesn't invoke a valid action or controller in ASP.NET MVC

Instead of it displaying the generic Resource Not Found ASP.NET error

I don't want to use the web config to handle this...

Is there any kind of routing magic I can do to catch any invalid urls?

Update: I tried the answer given... however I still get the ugly resource not found message...

Another update Ok apparently something changed in RC1.. I've even tried specifically trapping 404 on an httpexception and it still just gives me the resource not found page

I've even used mvcContrib's resuce's feature and nothing same problem....any ideas anyone..please before I go nuts

+1  A: 

Just add catch all route at the end of the routes table and display whatever page you want with it.

http://stackoverflow.com/questions/310580/how-can-i-make-a-catch-all-route-to-handle-404-page-not-found-queries-for-asp-n

Alex Reitbort
I tried this however, I still get the ugly ASP.NET default Resource Not Found Message..
dswatik
I don't find a definitive (and flexible!!) solution to this problem neither in this answer nor on the link provided.
Peter
Neither do I...this seems like kind of a hacky answer. I'm looking more for a way to make customErrors behave like they do in WebForms. Any ideas?
JC Grubbs
A: 

Firstly, you'll want an error page which is located in the Views/Shared. You can call it whatever you like - I personally find Error.aspx to be fine though (you might want to have a different name if you are trapping different types of error and don't want to display the same content). Then, within your controller class you can use the [HandleError] attribute (at either the class or action level) to define how errors should be dealt with.

Scott Guthrie has a good rundown on his site.

Zac
Thanks; however please read the question again... I want to trap 404... MVC is not letting me it keeps giving me the resource not found page when I told it to specifically go to the error page when 404
dswatik
+5  A: 

I found this the best article for me: http://www.genericerror.com/blog/2009/01/27/ASPNetMVCCustomErrorPages.aspx

I got my error handling to work by creating an ErrorController that returns the views in this article. I also had to add the "Catch All" to the route in global.asax.

I cannot see how it will get to any of these error pages if it is not in the web.config..? My web.config had to specify: customErrors mode="On" defaultRedirect="~/Error/Unknown" and then I also added: error statusCode="404" redirect="~/Error/NotFound"

Hope this helps.

Jack Smit
A: 

I had the same problem, the thing you have to do is, instead of adding the customErrors attribute in the web.config file in your Views folder, you have to add it in the web.config file in your projects root folder

SmokeIT