Handling route errors in ASP.NET MVC

蓝咒 提交于 2019-12-04 04:25:58

If your route is not found, you want to handle it as a normal HTTP 404 error.

If you only add the [HandleError] attribute to your class or action, MVC will look for an Error view in your views folder.

You could also add an ErrorController or even a static page and add this to your Web.config:

<customErrors mode="On" >
    <error statusCode="404" redirect="/Error/PageNotFound/" />
</customErrors>

Or you could handle the HTTP 404 in your Global.asax.cs and route to an ErrorController programmatically. That's how I generally do it:

protected void Application_Error(object sender, EventArgs e)
{
    var ex = Server.GetLastError().GetBaseException();

    var routeData = new RouteData();

    if (ex.GetType() == typeof(HttpException))
    {
        var httpException = (HttpException)ex;

        switch (httpException.GetHttpCode())
        {
            case 404:
                routeData.Values.Add("action", "PageNotFound");
                break;
            default:
                routeData.Values.Add("action", "GeneralError");
                break;
        }
    }
    else
    {
        routeData.Values.Add("action", "GeneralError");
    }

    routeData.Values.Add("controller", "Error");
    routeData.Values.Add("error", ex);

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

You can define a route like this:

routes.MapRoute(
                "PageNotFound",
                "{*catchall}",
                new { controller = "Home", action = "PageNotFound" }
                );

Than make an action in a controller like this:

        public ActionResult PageNotFound()
        {
            ViewBag.Message = "Sorry, the page you requested does not exist.";
            return View();
        }

This route sould be added last, that way it will catch any request that can't be mapped.

HandleError attribute is used to catch exceptions that may occure within controller actions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!