gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:21:25 25 4
gpt4 key购买 nike

我必须从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com