asp.net - ASP .NET Core : Routing. 开头的 url 中有多个类别

标签 asp.net asp.net-core asp.net-core-mvc asp.net-core-1.0 asp.net-core-routing

我必须从 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"
                });
        });

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

在 Controller 的 Action 中:
    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.

关于asp.net - ASP .NET Core : Routing. 开头的 url 中有多个类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42331841/

相关文章:

c# - 如何使用 mvc 6、asp.net 5 注册全局过滤器

c# - 在 C# 中为泛型类型扩展返回 null

asp.net - 使用 https 时 IIS 7 错误 "A specified logon session does not exist. It may already have been terminated."

linux - 将两个 asp.net 核心应用程序部署到 nginx 的一个解决方案中

c# - 如何使用 ASP.NET Core RC2 MVC6 和 IIS7 获取当前 Windows 用户

c# - ASP.NET Core 自定义验证属性本地化

c# - 对 IHostingEnvironment 使用自定义名称

c# - 无法创建 asp net core 2.0 web api

c# - 更新 Excel 工作表时操作必须使用可更新查询

javascript - Asp Core +Angular 4 +VS 2017,从 webpack 模板转移到其他东西