404 Http error handler in Asp.Net MVC (RC 5)

MrByte picture MrByte · Sep 20, 2008 · Viewed 17.5k times · Source

How can I Handler 404 errors without the framework throwing an Exception 500 error code?

Answer

dave picture dave · Sep 20, 2008

http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx gives the following explanation:

Add a wildcard routing rule as your final rule:

routes.MapRoute("Error", 
                "{*url}", 
                new { controller = "Error", action = "Http404" });

Any request that doesn't match another rule gets routed to the Http404 action of the Error controller, which you also need to configure:

public ActionResult Http404(string url) {
    Response.StatusCode = 404;
    ViewData["url"] = url;
    return View();
}