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

时间:2019-07-13 19:37:25

标签: c# asp.net-core asp.net-core-2.0 asp.net-core-2.2 asp.net-core-routing

我有一个写在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);
    }
}

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

3 个答案:

答案 0 :(得分:2)

在控制器内部,您可以从AttributeRouteInfoControllerContext中读取ActionDescriptorAttributeRouteInfo有一个Name属性,其中包含您要查找的值:

public ActionResult Act(ActVM viewModel)
{
    switch (ControllerContext.ActionDescriptor.AttributeRouteInfo.Name)
    {
        // ...
    }

    return View(viewModel);
}

在剃刀视图中,可以通过ViewContext属性使用ActionDescriptor

@{
    var routeName = ViewContext.ActionDescriptor.AttributeRouteInfo.Name;
}

答案 1 :(得分:1)

对我来说,@krik-larkin 的答案不起作用,因为在我的情况下 AttributeRouteInfo 始终为空。

我改用以下代码:

var endpoint = HttpContext.GetEndpoint() as RouteEndpoint;
var routeNameMetadata = endpoint?.Metadata.OfType<RouteNameMetadata>().SingleOrDefault();
var routeName = routeNameMetadata?.RouteName;

答案 2 :(得分:0)

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

相关问题