有
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
我想让我的网址允许在开头输入公司名称,例如:
url: "{company}/{controller}/{action}/{id}"
所以我可以浏览页面,现在基地是一些公司。
- domain.com/company-ltd
- domain.com/company-ltd/products
- domain.com/company-ltd/edit
- domain.com/some-other-company-name-ltd/products
等等。
我怎样才能做到这一点?谢谢。
最佳答案
路线在图案的背面起作用;传入的 URL 与模式匹配,直到发现它匹配为止。
假设你不是在谈论可选的公司名称,你应该能够逃脱:
routes.MapRoute(
name: "Default With company",
url: "{company}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional
);
然后简单地确保所有方法都采用company
参数。但是,这在更简单的路由上会失败,因此请确保为根页面等设置默认值。如果您最终想要不涉及公司的其他路线,也可以使用特定于 Controller 的路线来满足这些路线:
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"));
确保它们到达您期望的位置。
关于c# - .net 路由开头的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17653421/