How do I get Route name from RouteData?

前端 未结 10 899
猫巷女王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:29

    If you're working with a small subset of important routes you need to check for (a special case or two) you can just do this :

    if (routeData.Route == RouteTable.Routes["gallery-route"])
    {
       // current route is 'gallery-route'
    }
    

    A common reason for needing the route name is for debugging purposes. A quick and dirty way to do this follows - but you'll need to add each route name to the array of names. Should be fine for debugging - especially if the code isn't running during production.

    // quick and dirty way to get route name
    public string GetRouteName(RouteData routeData) 
    {
        foreach (string name in new [] { "gallery-route", 
                                         "products-route", 
                                         "affiliate-route", 
                                         "default" }) 
        {
            if (routeData.Route == RouteTable.Routes[name])
            {
                return name;
            }
        }
        return "UNKNOWN-ROUTE";   // or throw exception
    }
    

    For anything beyond this you should take the (minimal) time needed for @haacked's solution.

提交回复
热议问题