views:

1557

answers:

1

ASP.NET MVC routes have names when mapped:

routes.MapRoute(
 "Debug", // Route name -- how can I use this later????
 "debug/{controller}/{action}/{id}",
 new { controller = "Home", action = "Index", id = string.Empty } );

Is there a way to get the route name, e.g. "Debug" in the above example? I'd like to access it in the controller's OnActionExecuting so that I can set up stuff in the ViewData when debugging, for example, by prefixing a URL with /debug/...

+14  A: 

The route name is not stored in the route unfortunately. It is just used internally in MVC as a key in a collection. I think this is something you can still use when creating links with HtmlHelper.RouteLink for example (maybe somewhere else too, no idea).

Anyway, I needed that too and here is what I did:

public static class RouteCollectionExtensions
{
    public static Route MapRouteWithName(this RouteCollection routes,
    string name, string url, object defaults, object constraints)
    {
        Route route = routes.MapRoute(name, url, defaults, constraints);
        route.DataTokens = new RouteValueDictionary();
        route.DataTokens.Add("RouteName", name);

        return route;
    }
}

So I could register a route like this:

routes.MapRouteWithName(
    "myRouteName",
    "{controller}/{action}/{username}",
    new { controller = "Home", action = "List" }
    );

In my Controller action, I can access the route name with:

RouteData.DataTokens["RouteName"]

Hope that helps.

Nicolas Cadilhac
Cool workaround, though it seems like an oversight that MVC doesn't give access to it. You're right - you can create a route link by specifying the name, so it is stored somewhere :-)
Mike Scott
This isn't the purpose of the route name in the first place. The name is meant to provide an index when generating an URL using Routing that allows you to specify which route to use. DataTokens is really the right way to do that. For example, suppose you have multiple "Debug" routes. You couldn't use name for it anyways. But you can always create your own data tokens. Routing ignores data tokens but passes them along so your code can do the interpretation of what they mean.
Haacked