ASP .NET Core:路由。开始时 url 中的多个类别

mok*_*995 4 asp.net asp.net-core-mvc asp.net-core asp.net-core-1.0 asp.net-core-routing

我必须从 URL 传递用户请求,例如:

site.com/events/2017/06/wwdc.html
Run Code Online (Sandbox Code Playgroud)

或更常见的:

site.com/category1/subcategory1/subcategory2/...../subcategoryN/page-title.html
Run Code Online (Sandbox Code Playgroud)

例如

site.com/cars/tesla/model-s/is-it-worth-it.html
Run Code Online (Sandbox Code Playgroud)

ArticlesController用行动Index(string title)或类似的东西。

在编译时我不知道我会有多少段。但我知道,URL 将以/{pageTitle}.html. 主要问题是默认的 asp.net 核心路由不允许我写类似的东西{*}/pageTitle.html

是否可以?

Gui*_*sdy 5

这是可能的,你几乎做到了。

路线是

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "all",
                template: "{*query}",
                defaults: new
                {
                    controller = "Index",
                    action = "ArticlesController"
                });
        });
Run Code Online (Sandbox Code Playgroud)

编辑template: "{*query:regex(.+/.+\\.html$)}"将确保至少给出一个类别并且标题以 .html 结尾

在控制器的动作中:

    public IActionResult Index(string query)
    {
        string[] queryParts = query.Split(new char[] { '/' });
        string title = queryParts[queryParts.Length - 1];
        string[] categories = queryParts.Take(queryParts.Length - 1).ToArray();

        // add your logic about the title and the categories

        return View();
    }
Run Code Online (Sandbox Code Playgroud)

请参阅文档

专用的常规路由通常使用诸如 {*article} 之类的包罗万象的路由参数来捕获 URL 路径的剩余部分。这可能会使路由“过于贪婪”,这意味着它会匹配您打算与其他路由匹配的 URL。将“贪婪”路由稍后放在路由表中以解决此问题。