asp.net-mvc 如何在 ASP.NET MVC 的控制器中获取路由名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/363211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:12:34  来源:igfitidea点击:

How can I get the route name in controller in ASP.NET MVC?

asp.net-mvcmodel-view-controllerrouting

提问by Mike Scott

ASP.NET MVC routes have names when mapped:

ASP.NET MVC 路由在映射时具有名称:

routes.MapRoute(
    "Debug", // Route name -- how can I use this later????
    "debug/{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = string.Empty } );

Is there a way to get the route name, e.g. "Debug" in the above example? I'd like to access it in the controller's OnActionExecuting so that I can set up stuff in the ViewData when debugging, for example, by prefixing a URL with /debug/...

有没有办法获取路线名称,例如上面示例中的“调试”?我想在控制器的 OnActionExecuting 中访问它,以便我可以在调试时在 ViewData 中设置内容,例如,通过在 URL 前加上 /debug/...

回答by Nicolas Cadilhac

The route name is not stored in the route unfortunately. It is just used internally in MVC as a key in a collection. I think this is something you can still use when creating links with HtmlHelper.RouteLink for example (maybe somewhere else too, no idea).

不幸的是,路线名称未存储在路线中。它只是在 MVC 内部用作集合中的键。我认为这是您在使用 HtmlHelper.RouteLink 创建链接时仍然可以使用的东西,例如(也许在其他地方也是如此,不知道)。

Anyway, I needed that too and here is what I did:

无论如何,我也需要它,这就是我所做的:

public static class RouteCollectionExtensions
{
    public static Route MapRouteWithName(this RouteCollection routes,
    string name, string url, object defaults, object constraints)
    {
        Route route = routes.MapRoute(name, url, defaults, constraints);
        route.DataTokens = new RouteValueDictionary();
        route.DataTokens.Add("RouteName", name);

        return route;
    }
}

So I could register a route like this:

所以我可以注册一个这样的路线:

routes.MapRouteWithName(
    "myRouteName",
    "{controller}/{action}/{username}",
    new { controller = "Home", action = "List" }
    );

In my Controller action, I can access the route name with:

在我的 Controller 操作中,我可以使用以下命令访问路由名称:

RouteData.DataTokens["RouteName"]

Hope that helps.

希望有帮助。

回答by Alan Shaw

If using the standard MapRoute setting like below:

如果使用标准 MapRoute 设置,如下所示:

routes.MapRoute(    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

...this will work in the view...

...这将在视图中工作...

var routeName = Url.RequestContext.RouteData.Values["action"].ToString();

回答by Alexander

You could pass route name through route values using default value of additional parameter:

您可以使用附加参数的默认值通过路由值传递路由名称:

routes.MapRoute(
    name: "MyRoute",
    url: "{controller}/{action}/{id}",
    defaults: new { routeName = "MyRoute", controller = "Home", action = "Index", id=UrlParameter.Optional }
);

Then, it is possible to get passed value from controller context:

然后,可以从控制器上下文中获取传递的值:

string routeName = ControllerContext.RouteData.Values["routeName"].ToString();

回答by logicalguy

This does not directlyanswer the question (if you want to be pedantic); however, the real objective seems to be to get a route's base URL, given a route name. So, this is how I did it:

这并不能直接回答问题(如果你想学究);然而,真正的目标似乎是在给定路由名称的情况下获取路由的基本 URL。所以,我是这样做的:

My route was defined in RouteConfig.csas:

我的路线定义RouteConfig.cs为:

routes.MapRoute(
            name: "MyRoute",
            url: "Cont/Act/{blabla}",
            defaults: new { controller = "Cont", action = "Act"}
        );

And to get the route's base URL:

并获取路由的基本 URL:

var myRoute = Url.RouteUrl("MyRoute", new { blabla = "blabla" }).Replace("blabla", "");

It gave me the route's base URL that I wanted:

它给了我我想要的路由的基本 URL:

/Cont/Act/

Hope this helps.

希望这可以帮助。

回答by ajbeaven

An alternative solution could be to use solution configurations:

另一种解决方案可能是使用解决方案配置:

protected override OnActionExecuting()
{
    #if DEBUG

        // set up stuff in the ViewData

    #endif

    // continue
}

There shouldn't really ever be a need to reference the route name like this - which I suppose is why MVC makes it so difficult to do this sort of thing.

真的不需要像这样引用路由名称 - 我想这就是为什么 MVC 使这种事情变得如此困难的原因。

回答by Мишка Коробков

another option - use MapRoute with string[] namespaces argument, then you can see your namespaces as RouteData.DataTokens["Namespaces"]

另一个选项 - 将 MapRoute 与 string[] 命名空间参数一起使用,然后您可以将命名空间视为 RouteData.DataTokens["Namespaces"]