在 ASP NET MVC Core 中将 routdata 保留在不同控制器(使用锚标记助手)的生成 url 中

Keep routdata in generate urls to different controller (using anchor tag helper) in ASP NET MVC Core

在 startup.cs 文件中,我更改了默认的 MapRoute

routes.MapRoute(
                name: "default",
                template: "{controller=home}/{company=-1}/{action=index}/{id?}");

当您从正在访问的同一控制器创建 url links(使用锚点 tagHelper)时,它可以正常工作。

但是当我为另一个控制器创建 link 时,我正在失去公司价值

<a asp-action="index" asp-controller="AnotherController" >TEST</a>

例如,如果我正在访问 http:// localhost/testcontroller/22 (Company=22) 生成的URL到另一个controller是http://localhost/AnotherController 生成的URL到相同的控制器是正确的:http://localhost/testcontroller/22/otherAction

我不知道这是否是最佳实践,我可以使用 asp-route- prefix 属性解决它。

<a asp-action="index" asp-controller="test" asp-route-company="@ViewContext.RouteData.Values["company"]">TEST</a>