How do I get Route name from RouteData?

前端 未结 10 890
猫巷女王i
猫巷女王i 2021-02-05 02:03

I have several routes defined in my Global.asax;

When I\'m on a page I need to figure out what is the route name of the current route, because route name drives my site

10条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 02:24

    RouteCollection maintains a private dictionary of named routes.

    Route names can be coaxed out of it by

    1. using reflection to retrieve the value of the private field and
    2. querying the dictionary for the item whose value is the route.

    The extension method below follows this process:

    public static string Name(this RouteBase original)
    {
        var routes = System.Web.Routing.RouteTable.Routes;
    
        if (routes.Contains(original))
        {
            var namedMapField = routes.GetType().GetField("_namedMap", BindingFlags.NonPublic | BindingFlags.Instance);
            var namedMap = namedMapField.GetValue(routes) as Dictionary;
    
            var query = 
                from pair in namedMap 
                where pair.Value == original 
                select pair.Key;
    
            return query.Single();
        }
    
        return string.Empty;
    }
    

提交回复
热议问题