Snake Eyes
Snake Eyes

Reputation: 16764

How to get route url properties by route name using C# code?

As we know, a route is mapped in Global.asax file, like:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

There is a method/class where I can access route url properties name by providing a route name ?

For example, for Default, I want to call something like

public object[] GetRoutePropertiesByName(string name) {
    // process here the `controller`, `action`, `id` // there might be also other values
}

Upvotes: 2

Views: 2946

Answers (1)

Xavier Poinas
Xavier Poinas

Reputation: 19743

This is how you can get a route by name:

RouteTable.Routes[routeName]

From there you can get some of the route properties:

var route = RouteTable.Routes[routeName] as Route;
if (route != null)
{
    var url = route.Url;        
    var controller = route.Defaults["controller"] as string;
    var action = route.Defaults["action"] as string;
    // ...
}

Upvotes: 2

Related Questions