DOTNET核心2 - 捕获所有路线? (* MenuPath / pageUrl.html)

问题描述 投票:0回答:1

有没有办法使用routeattribute创建一个catch所有路由?

在我的网站上,我有预定义的路线,如/ cars / insurances / best

但是,由于我们有一个带有动态菜单和页面网址的CMS,我需要使用无限斜线捕获所有路径。

因此,如果我导航到/whatever/this/is/a/menupath/withapage.html,它应该转到我的Page方法。不应该要求withapage.html。

我尝试了以下路线,但它不起作用

[Route("{*menuPath}/{pageUrl.html?}")]
public async Task<IActionResult> Page(string menuPath, string pageUrl = null, CancellationToken token = default(CancellationToken))

在MVC 5中,我们使用GreedyRoute的这个设置:

    routes.Add(
            new GreedyRoute("{*menuPath}/{pageUrl}",
            new RouteValueDictionary(new { controller = "Page", action = "Index" }),
            new RouteValueDictionary(new { pageUrl = @"[0-9a-zA-ZøæåØÆÅ+_-]+.html" }),
            new MvcRouteHandler()));

        routes.Add(
            new GreedyRoute("{*menuPath}",
            new RouteValueDictionary(new { controller = "Page", action = "List" }),
            new MvcRouteHandler()));

dotnet core 2中有类似的东西吗?

c# routing .net-core
1个回答
2
投票

{*menuPath}是一个catch-all参数,它只能用作路径模板中的最后一个段。

我怀疑用纯属性路由可以实现你想要的东西。您希望使用任意数量的斜杠捕获URL部分到一个字符串参数,但斜杠对URL和路由具有非常特殊的含义。如果我在你的位置,我将通过以下方式解决它:

[Route("{*menuPathAndPage}")]
public async Task<IActionResult> Page(string menuPathAndPage, CancellationToken token = default(CancellationToken))
{
    var slashPos = menuPathAndPage.LastIndexOf('/');
    var menuPath = slashPos != -1 ? menuPathAndPage.Substring(0, slashPos) : menuPathAndPage;
    var pageUrl = slashPos != -1 ? menuPathAndPage.Substring(slashPos + 1) : String.Empty;

    //  ...
}

好吧,从纯粹主义的角度来看,它可能不是完美的解决方案,但这种方法应该对你有用。

© www.soinside.com 2019 - 2024. All rights reserved.