Getting information about the current Route
One of the things I needed when I started playing with ASP.NET MVC is getting info about the current Route. That’s easy when you’re on the controller, but what happens when you need that info on a module?
In these scenarios, the easiest way of achieving this is getting a reference to the current HttpContext, wrapping it up on an instance of type HttpContextWrapper and then passing it to GetRouteData method of the existing route collection. Here’s some demo code that does just that:
var route = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
var controllerName = route.Values["controller"];
var actionName = route.Values["action"];
After getting the RouteData associated with the current request, you can easilly get all the information associated with the current route. In this case, I’ve just recovered the current controller and action which had been set as parameter variables on the url pattern. Not hard, right?