Asp.net mvc 2 MVC2为什么只有我的第一条路线被识别?

Asp.net mvc 2 MVC2为什么只有我的第一条路线被识别?,asp.net-mvc-2,routes,Asp.net Mvc 2,Routes,所以现在我有两条路线: routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

所以现在我有两条路线:

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

           routes.MapRoute(
               "Legos",
               "{controller}/{action}/{page}",
               new { controller = "Legos", action = "Lego", page = UrlParameter.Optional });
如果我去
www.website.com
,我可以很好地看到我的主页,但是我的
Legos
路线不起作用。像wise一样,如果我把我的
乐高积木
路线放在上面,我可以去
www.website.com/Legos/Lego/1
很好,但是去www.website.com会出错(如下),我需要手动去
www.website.com/Home/Index
查看我的主页

错误:

The parameters dictionary contains a null entry for parameter 'page' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Errors(Int32, System.String)' in 'stuff.Controllers.Legos'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters

为什么会这样?

原因是两条路由具有相同数量的参数且没有约束,因此路由处理程序无法区分入站请求中的两条路由-它将只使用第一个匹配项(即,先添加到路由表中的那个)

如果你正确地区分了你的路线,那么它就会起作用。例如,您可以尝试从“默认”路由中删除“id”可选参数,并使“Legos”路由的“page”部分成为必需的(因为端点工作似乎是必需的,无论如何这是最佳做法):

这意味着一个带有两个参数(即Home/Index)的url将与“Legos”路由不匹配,因为它缺少所需的“page”参数-然后它将测试“Default”路由,这将成功,因为“Home/Index”匹配它期望的“{anything}/{anything}”格式

您的另一个选项是向其中一个路由添加路由约束-例如,您可以使“page”仅接受数字,因此如果传入请求看起来像{anything}/{anything}/{numeric},它将匹配“Legos”路由,但如果它不是数字,它将不匹配约束,而是会命中默认路由:

routes.MapRoute(
"Legos",
url: "{controller}/{action}/{page}",
defaults: new { controller = "Legos", action = "Lego" },
constraints: new { page = @"([0-9]+)" } ); // constrain to "one or more numbers" - constraints are simply regular expressions

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

当然,这个特殊解决方案的“问题”是,如果你有一个数字id(让我们面对它,大多数是),你想用于“默认”路线,它最终会被“乐高”路线捕获

我很确定默认的catchall路由应该是last。但即使是,我也会列出错误。
routes.MapRoute(
"Legos",
url: "{controller}/{action}/{page}",
defaults: new { controller = "Legos", action = "Lego" },
constraints: new { page = @"([0-9]+)" } ); // constrain to "one or more numbers" - constraints are simply regular expressions

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