Handling route errors in ASP.NET MVC

北城余情 提交于 2019-12-21 12:18:37

问题


I understand how to set up my own routes, but how does one handle routes that fall through the cracks of the routing table? I mean, I guess the default {controller}/{action}/{id} route could be a generic catchall, but I'm not sure if that's the way to go. I like letting my users know they've requested data/a 'page' that doesn't exist.

Is this where the [HandleError] filter comes in? How does that work, exactly?


回答1:


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));
}



回答2:


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.



来源:https://stackoverflow.com/questions/4832906/handling-route-errors-in-asp-net-mvc

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