如何使用ASP.NET Core获取当前路由名称?

问题描述 投票:4回答:2

我有一个写在ASP.NET Core 2.2框架顶部的应用程序。

我有以下控制器

public class TestController : Controller
{
    [Route("some-parameter-3/{name}/{id:int}/{page:int?}", Name = "SomeRoute3Name")]
    [Route("some-parameter-2/{name}/{id:int}/{page:int?}", Name = "SomeRoute2Name")]
    [Route("some-parameter-1/{name}/{id:int}/{page:int?}", Name = "SomeRoute1Name")]
    public ActionResult Act(ActVM viewModel)
    {
        // switch the logic based on the route name

        return View(viewModel);
    }
}

如何在操作和/或视图中获取路线名称?

c# asp.net-core asp.net-core-2.2 asp.net-core-routing
2个回答
7
投票

在控制器内部,您可以从AttributeRouteInfoAttributeRouteInfo中读取ControllerContextControllerContext具有ActionDescriptor属性,其中包含您要查找的值:

ActionDescriptor

在Razor视图中,可以通过AttributeRouteInfo属性使用Name

Name

0
投票

您还应该能够查看http请求对象的上下文,该对象应该具有路径段,完整url等。

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