ASP .NET Core:路由。 url 开头的多个类别

ASP .NET Core: Routing. Multiple categories in url at begining

我必须传递来自以下 URL 的用户请求:

site.com/events/2017/06/wwdc.html

或更常见:

site.com/category1/subcategory1/subcategory2/...../subcategoryN/page-title.html

例如

site.com/cars/tesla/model-s/is-it-worth-it.html

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

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

的东西

可能吗?

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

路线是

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

EDIT: 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();
    }

查看documentation

Dedicated conventional routes often use catch-all route parameters like {*article} to capture the remaining portion of the URL path. This can make a route 'too greedy' meaning that it matches URLs that you intended to be matched by other routes. Put the 'greedy' routes later in the route table to solve this.