多参数 MVC 路由

Multiple Parameters MVC routing

我正在制作一个类似图书馆的网站。在这个库中,一篇文章可以有一个类别,并且该类别最多可以有 2 个父类别,例如:"World > Country > City"。

我想将所有视图的所有显示都保留到名为 LibraryController 的所有文章的单个控制器。并且正在使用的 2 个操作是 Article(string id)Category(string[] ids)

要查看名为 "The Templar Order" 的文章,用户必须输入:/library/article/the-templar-order

好的,现在是类别。我脑子里有两种方法,这个例子是查看 "City" 类别:

  1. 简单的方法:/library/world-country-city
  2. 我想要的那个:/library/world/country/city
  3. 我不想要的,因为它变得太笨拙了:/library/category/world/country/city

但我对如何创建一条采用 3 个参数且基本上不执行任何操作的路由感到有点困惑。并且除了第一个参数 "world" 其余的应该是可选的,像这样: "/library/world/" > "/library/world/country/" > "/library/world/country/city/"

那么我将如何创建这样一条路线?

解决方案

RouteConfig.cs

// GET library/article/{string id}
routes.MapRoute(
    name: "Articles",
    url: "Library/Article/{id}",
    defaults: new { controller = "Library", action = "Article", id = "" }
    );

// GET library/
routes.MapRoute(
    name: "LibraryIndex",
    url: "Library/",
    defaults: new { controller = "Library", action = "Index" }
    );

// GET library/category/category/category etc.
routes.MapRoute(
    name: "Category",
    url: "Library/{*categories}",
    defaults: new { controller = "Library", action = "Category" }
    );

您可以通过以下两条途径实现。

// GET library/article/the-templar-order
routes.MapRoute(
     name: "Articles",
     url: "Library/Article/{id}",
     defaults: new { controller = "Library", action = "Article" }
 );

// GET library/world/country/city
routes.MapRoute(
     name: "Category",
     url: "Library/{*categories}",
     defaults: new { controller = "Library", action = "Category" }
 );

并对目标动作稍作修改

public ActionResult Category(string categories) {
    categories = categories ?? string.Empty;
    var ids = categories.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);
    //...other code
}