如何在ASP.NET Core中获取当前路由名称?

15

我有一个应用程序,它是在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);
    }
}

如何在Action和/或View中获取路由名称?

4个回答

16
在控制器内部,可以从ControllerContextActionDescriptor中读取AttributeRouteInfoAttributeRouteInfo有一个Name属性,其中包含您要查找的值:
public ActionResult Act(ActVM viewModel)
{
    switch (ControllerContext.ActionDescriptor.AttributeRouteInfo.Name)
    {
        // ...
    }

    return View(viewModel);
}

在 Razor 视图中,ViewContext 属性可以获取 ActionDescriptor

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

12

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

我使用了以下代码:

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

1
完全和我的情况一样。这应该被标记为答案。谢谢。 - Andrey Kusnetsov

2

对Kirk Larkin答案的一个小修正。有时您必须使用Template属性而不是Name:

var ari = ControllerContext.ActionDescriptor.AttributeRouteInfo;
var route = ari.Name ?? ari.Template;

1

针对 .NET 6:

接受的答案对我也不起作用。

然而,这个可以解决问题:

var routeName = (HttpContext.GetEndpoint() as RouteEndpoint).RoutePattern.RawText;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接