c# - .net 路由开头的可选参数

标签 c# .net asp.net-mvc-4 configuration routes

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/

相关文章:

c# - 将 ASP.Net Core 集成到 WPF 应用程序中

c# - 匹配并替换字符串中的第一个和最后一个字符

c# - checkboxlist - 如何在不设置选定值的情况下填充它

c# - 如何使用 .NET 在 Windows 窗体中显示 Windows 文件夹内容?

jquery - 使用 PagedList 分页局部 View

asp.net-mvc - 默认页面重定向到登录 - MVC 4

c# - 递归快速排序遇到 StackOverflowException

c# - 使用 c# .net 将两个视频合二为一

c# - 匿名类型(类特性)

c# - 为另一个时区的服务器调整 DateTime.Now