How do I get Route name from RouteData?

前端 未结 10 1049
猫巷女王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条回答
  •  萌比男神i
    2021-02-05 02:22

    FWIW, since the extensions and example shown by @Simon_Weaver are MVC-based and the post is tagged with WebForms, I thought I'd share my WebForms-based extension methods:

        public static void MapPageRouteWithName(this RouteCollection routes, string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess = true,
                RouteValueDictionary defaults = default(RouteValueDictionary), RouteValueDictionary constraints = default(RouteValueDictionary), RouteValueDictionary dataTokens = default(RouteValueDictionary))
        {
            if (dataTokens == null)
                dataTokens = new RouteValueDictionary();
    
            dataTokens.Add("route-name", routeName);
            routes.MapPageRoute(routeName, routeUrl, physicalFile, checkPhysicalUrlAccess, defaults, constraints, dataTokens);
        }
    
        public static string GetRouteName(this RouteData routeData) 
        {
            if (routeData.DataTokens["route-name"] != null)
                return routeData.DataTokens["route-name"].ToString();
            else return String.Empty;
        }
    

    So now in Global.asax.cs when you're registering your routes, instead of doing like routes.MapPageRoute(...) - instead use the extension method and do routes.MapPageRouteWithName(...)

    Then when you want to check what route you're on, simply do Page.RouteData.GetRouteName()

    That's it. No reflection, and the only hard-coded references to "route-name" are in the two extension methods (which could be replaced with a const if you really wanted to).

提交回复
热议问题