views:

108

answers:

2

If we use this standard route:

routes.MapRoute(
    "Default",                                              // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

and within Windows 2008 IIS7 with MVC 2 setup we go to here:

"http://www.mywebsite.com/SomePageThatDoesNotExist.aspx"

and then under the Application_Error method we have this:

protected void Application_Error(object sender, EventArgs e)
{
     Response.Clear();

     RouteData routeData = new RouteData();
     routeData.Values.Add("controller", "Error");
     routeData.Values.Add("action", "Index");

     Server.ClearError();

     IController errorController = new ErrorController();
     errorController.Execute(new RequestContext(
         new HttpContextWrapper(Context), routeData));
}

Instead of getting a route and a page we expect, we get a nasty 404 Server error page. Any idea how to capture url errors and direct them to a page of our choice?

+2  A: 

MVC has HandleErrorAttribute. You can customize it to handle only 404 or other types of error.

[HandleError(ExceptionType = typeof(ResourceNotFoundException),
    View = "ResourceNotFound")]

You can associate different type of exception with different views. In the above example, when the action throw ResourceNotFoundException, it will render ResourceNotFound view.

Here is a link on how to handle 404 errors, the author provided a couple of ways to handle it.

J.W.
+2  A: 

You can do it in the web.config like this.

    <customErrors mode="Off" defaultRedirect="~/Error/">
        <error statusCode="403" redirect="~/Error/Forbidden" />
        <error statusCode="404" redirect="~/Error/PageNotFound" />
    </customErrors>
MHinton