【问题标题】:How can I get the current route name with ASP.NET Core?如何使用 ASP.NET Core 获取当前路由名称?
【发布时间】:2019-11-23 02:59:35
【问题描述】:

我有一个基于 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


    【解决方案1】:

    对 Kirk Larkin 答案的小修正。有时您必须使用模板属性而不是名称:

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

    【讨论】:

      【解决方案2】:

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

      我使用了以下代码:

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

      【讨论】:

      • 在我的情况下完全一样。这应该被标记为答案。谢谢
      【解决方案3】:

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

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

      在 Razor 视图内部,ActionDescriptor 可通过 ViewContext 属性获得:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-04
        • 2016-05-09
        • 1970-01-01
        • 2020-04-02
        相关资源
        最近更新 更多