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?


~ by Luis Abreu on July 24, 2008.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: