我们有一个这样的路由配置:
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "About",
url: "{controller}/{action}/{aboutId}",
defaults: new { controller = "Home", action = "About" }
);
routes.MapRoute(
name: "Contact",
url: "{controller}/{action}/{contactId}",
defaults: new { controller = "Home", action = "Contact" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
您会注意到有两条路线具有一个强制性的额外参数。路线About
和Contact
.
在我们的应用程序中,我们有两个 url
www.myapp.com/Home/About/2
效果很好。但是当我们浏览浏览器时,www.myapp.com/Home/Contact/5
我们得到了可怕的路由异常:
The parameters dictionary contains a null entry for parameter 'contactId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Contact(Int32)' in 'RoutingTest.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
如果我们改变路由的顺序,使它看起来像这样:
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Contact",
url: "{controller}/{action}/{contactId}",
defaults: new { controller = "Home", action = "Contact" }
);
routes.MapRoute(
name: "About",
url: "{controller}/{action}/{aboutId}",
defaults: new { controller = "Home", action = "About" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
然后Contact
网址有效,但About
网址无效。
HomeController 看起来像这样:
public class HomeController : Controller {
public ActionResult Index() {
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About(int aboutId) {
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact(int contactId) {
ViewBag.Message = "Your contact page.";
return View();
}
}
这似乎意味着无论控制器动作的名称如何,两个路由不能具有相同数量的参数。如果两个控制器动作有一个同名的参数,那么一切正常。我知道我可以开始做一些非常棘手的事情来解决这个问题,例如调用所有参数相同的名称或为操作提供无意义的参数来更改参数的数量,但我实际上想知道幕后发生了什么。
我该如何解决这个问题?