简体   繁体   English

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

[英]How can I get the current route name with ASP.NET Core?

I have an application that is written on the top of ASP.NET Core 2.2 framework.我有一个写在 ASP.NET Core 2.2 框架之上的应用程序。

I have the following controller我有以下控制器

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);
    }
}

How can I get the route name in the action and/or the view?如何在操作和/或视图中获取路线名称?

Inside of a controller, you can read the AttributeRouteInfo from the ControllerContext 's ActionDescriptor .在控制器内部,您可以从ControllerContextActionDescriptor读取AttributeRouteInfo AttributeRouteInfo has a Name property, which holds the value you're looking for: AttributeRouteInfo有一个Name属性,它保存您要查找的值:

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

    return View(viewModel);
}

Inside of a Razor view, the ActionDescriptor is available via the ViewContext property:在 Razor 视图内部, ActionDescriptor可通过ViewContext属性获得:

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

For me the answer by @krik-larkin didn't work as AttributeRouteInfo was always null in my case.对我来说,@krik-larkin 的答案不起作用,因为在我的情况下AttributeRouteInfo始终为 null。

I used the following code instead:我改用以下代码:

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

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

Small correction to Kirk Larkin answer.对 Kirk Larkin 回答的小修正。 Sometimes you have to use Template property instead of Name:有时您必须使用模板属性而不是名称:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM