如何使用ASP.NET Core获取当前路由名称? [英] How can I get the current route name with ASP.NET Core?

查看:192
本文介绍了如何使用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?

推荐答案

在控制器内部,您可以阅读

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获取当前路由名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆