55

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

8 Answers 8

76

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"]
Sign up to request clarification or add additional context in comments.

5 Comments

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 :-)
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.
still it is an oversight for two reasons: first, people apparently find it useful and second, why does the MapRoute take the name as argument but when constructing a new route with a constructor there is no Name argument in it.
Here another very similar approach haacked.com/archive/2010/11/28/…
@mare When a framework doesn't include every possible feature that anyone could possibly want, that doesn't equate to an "oversight." And your second reason doesn't make any sense. That's like saying "Why does Dictionary<string, string>.Add() take key as an argument, but when constructing a new string with a constructor there is no key argument in it?" The route name is an identifier for the route. It's not a property of the route.
4

If using the standard MapRoute setting like below:

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

...this will work in the view...

var routeName = Url.RequestContext.RouteData.Values["action"].ToString();

Comments

1

You could pass route name through route values using default value of additional parameter:

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

Then, it is possible to get passed value from controller context:

string routeName = ControllerContext.RouteData.Values["routeName"].ToString();

Comments

0

This does not directly answer the question (if you want to be pedantic); however, the real objective seems to be to get a route's base URL, given a route name. So, this is how I did it:

My route was defined in RouteConfig.cs as:

routes.MapRoute(
            name: "MyRoute",
            url: "Cont/Act/{blabla}",
            defaults: new { controller = "Cont", action = "Act"}
        );

And to get the route's base URL:

var myRoute = Url.RouteUrl("MyRoute", new { blabla = "blabla" }).Replace("blabla", "");

It gave me the route's base URL that I wanted:

/Cont/Act/

Hope this helps.

Comments

0

If you do not want to create an extension for this, you can simply add the DataToken in your current RouteConfig MapRoute call.

routes.MapRoute(
    name: "RouteName",
    url: "{param1}",
    constraints: new { param1 = "desired url" },
    defaults: new { controller = "Controller", action = "Action" }
    ).DataTokens.Add("Name", "RouteName");

Comments

-1

An alternative solution could be to use solution configurations:

protected override OnActionExecuting()
{
    #if DEBUG

        // set up stuff in the ViewData

    #endif

    // continue
}

There shouldn't really ever be a need to reference the route name like this - which I suppose is why MVC makes it so difficult to do this sort of thing.

Comments

-2

another option - use MapRoute with string[] namespaces argument, then you can see your namespaces as RouteData.DataTokens["Namespaces"]

Comments

-2

o get the route name in a controller in ASP.NET MVC, you can use the RouteData object. The RouteData object contains information about the current request, including the route name that was used to match the request.

To get the route name, you can use the RouteData.RouteName property.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.