2

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/编辑
  • domain.com/some-other-company-name-ltd/products

等等。

我怎么能做到这一点?谢谢。

4

1 回答 1

0

路线在模式的后面起作用;传入的 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"));

以确保他们将前往您期望的位置。

于 2013-07-15T11:50:23.803 回答