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

前端 未结 6 2035
我在风中等你
我在风中等你 2020-11-28 22:45

ASP.NET MVC routes have names when mapped:

routes.MapRoute(
    \"Debug\", // Route name -- how can I use this later????
    \"debug/{controller}/{action}/{i         


        
6条回答
  •  一向
    一向 (楼主)
    2020-11-28 23:08

    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).

    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:

    RouteData.DataTokens["RouteName"]
    

    Hope that helps.

提交回复
热议问题