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/...
Configure a Route Every MVC application must configure (register) at least one route configured by the MVC framework by default. You can register a route in RouteConfig class, which is in RouteConfig. cs under App_Start folder. The following figure illustrates how to configure a route in the RouteConfig class .
Route Name: A route is a URL pattern that is mapped to a handler. A handler can be a controller in the MVC application that processes the request. A route name may be used as a specific reference to a given route.
Default Route: The default ASP.NET MVC project templates add a generic route that uses the following URL convention to break the URL for a given request into three named segments. URL: "{controller}/{action}/{id}" This route pattern is registered via a call to the MapRoute() extension method of RouteCollection.
RouteData is a property of the base Controller class, so RouteData can be accessed in any controller. RouteData contains route information of a current request. You can get the controller, action or parameter information using RouteData as shown below. Example: RouteData in MVC.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With