1

In my ASP.Net MVC2, how do I create a wide 404 page?

Meaning every single time someone tries to enter a non-existent view/page, he's redirected to this error page of my choosing?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254

1 Answers1

2

Use the standard ASP.NET error pages (activate in web.config):

<customErrors mode="On|RemoteOnly" defaultRedirect="/error/problem">
    <error statusCode="404" redirect="/error/notfound"/>
    <error statusCode="500" redirect="/error/problem"/>
</customErrors>

And/or create an error handling controller and use it with a catchall route:

ErrorController.cs:

public class ErrorController : Controller
{
    public ActionResult NotFound(string aspxerrorpath)
    {
        // probably you'd like to log the missing url. "aspxerrorpath" is automatically added to the query string when using standard ASP.NET custom errors
        // _logger.Log(aspxerrorpath); 
        return View();
    }
}

global.asax:

// This route catches all urls that do not match any of the previous routes.
// So if you registered the standard routes, somthing like "/foo/bar/baz" will
// match the "{controller}/{action}/{id}" route, even if no FooController exists
routes.MapRoute(
     "Catchall",
     "{*catchall}",
     new { controller = "Error", action = "NotFound" }
);
davehauser
  • 5,844
  • 4
  • 30
  • 45
  • I've added the routes.MapRoute() and it's not working. Any ideas why? I've already made the controller and the view. – Sergio Tapia Aug 02 '10 at 02:13
  • The Catchall route does only catch routes that don't match any other route. So if you have the standard route "{controller}/{action}/{id}", every Url looking something like this "/foo/bar/baz" will match that route, even if no FooController exists. For catching all missing controllers/actions the simplest solution is to go with the ASP.NET custom errors. You either use static files for the error page or create a controller/action for that (using my sample above would then redirect you to the ErrorController and invoke the NotFound action). I edited my answer to include that. – davehauser Aug 02 '10 at 11:04
  • For more details about this subjct have a look at this question: http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/2577095#2577095 – davehauser Aug 04 '10 at 13:01