Core获取当前路由名称

Core获取当前路由名称

本文介绍了如何使用ASP.NET Core获取当前路由名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an application that is written on the top of ASP.NET Core 2.2 framework.

我有以下控制器

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?

推荐答案

在控制器内部,您可以阅读 AttributeRouteInfo 来自 ControllerContext ActionDescriptor . AttributeRouteInfo 具有 Name 属性,其中包含您要查找的值:

Inside of a controller, you can read the AttributeRouteInfo from the ControllerContext's ActionDescriptor. AttributeRouteInfo has a Name property, which holds the value you're looking for:

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

    return View(viewModel);
}

在Razor视图中,可以通过ActionDescriptor .rendering.viewcontext"rel =" nofollow noreferrer> ViewContext 属性:

Inside of a Razor view, the ActionDescriptor is available via the ViewContext property:

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

这篇关于如何使用ASP.NET Core获取当前路由名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 15:44