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