.Net MVC Routing Catchall not working

时间秒杀一切 提交于 2019-11-27 22:09:12

MVC routes are checked in the order that they are entered.

Mysite/blah will be found by the default route. The controller will be blah, and the action is index.

When you entered the mysite/blah/blah/blah/blah route you gave it a route it could not map the default route to and then your catchall route was called.

For those other examples, did you notice if they had some error filters setup? I'm pretty sure the default asp.net mvc site has some error handling attributes on the pages already.

Your first route will catch the most urls since you have defaults for the elements, you can visualize this using the route debugger from Phil Haack, see the link:

Route Debugger

Darin Dimitrov

In order to handle errors I used the Application_Error event in one of my projects:

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    HttpException httpException = exception as HttpException;
    if (httpException != null)
    {
        RouteData routeData = new RouteData();
        routeData.Values.Add("controller", "Error");
        routeData.Values.Add("action", "HttpError500");

            if (httpException.GetHttpCode() == 404)
            {
                routeData.Values["action"] = "HttpError404";
            }

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

This can also help when dealing with MVC catchall problems:

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

That is, where it says {id}, change it to {*id}. This allows the final id parameter to consume as much additional path as might be passed in. The default rule accepts this:

/person/name/joe

But not this:

/products/list/sortby/name

The second URL will throw a 404 without this modification to the route.

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