路线在模式的后面起作用;传入的 URL 与模式匹配,直到找到匹配的 URL。
假设您不是在谈论可选的公司名称,您应该能够逃脱:
routes.MapRoute(
name: "Default With company",
url: "{company}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional
);
然后简单地确保所有方法都带一个company
参数。但是,这在更简单的路由上会失败,因此请确保为诸如根等页面设置默认值。如果您最终需要不涉及公司的其他路线,也可以使用特定于控制器的路线来满足这些路线:
routes.MapRoute(
name: "Profile",
url: "profile/{action}/{id}",
defaults: new { controller = "Profile", action = "Index", id = UrlParameter.Optional
);
在不太具体的公司之前。
请注意,您可以使用 NUnit 和 MvcContrib.TestHelper 在 .net 中非常轻松地测试这些路由,例如:
"~/company/".WithMethod(HttpVerbs.Get)
.ShouldMapTo<Controller.HomeController>(x =>
x.Index("company"));
"~/company/products/".WithMethod(HttpVerbs.Get)
.ShouldMapTo<Controller.ProductsController>(x =>
x.Index("company"));
以确保他们将前往您期望的位置。