MVC: Accessing the RouteData inside of your C# code


You want to perform some dynamic processing in your code and you need to determine either the name of the current controller or the current action or both. Enter the object ControllerContext.RouteData.

Using the ControllerContext.RouteData

Inside of your code you can use the following syntax to access the controller or action:

var controller = ControllerContext.RouteData.Values[“controller”];
var action = ControllerContext.RouteData.Values[“action”];

If you are inside of another class, you might need to access it via the current request, e.g.

var controller = HttpContext.Current.Request.RequestContext.RouteData.Values[“controller”];
var action = HttpContext.Current.Request.RequestContext.RouteData.Values[“action”];

Because the Values is a dictionary of key/value pairs you could easily use a for/each loop to iterate through them as follows:

foreach (KeyValuePair kvp in ControllerContext.RouteData.Values)
string key = kvp.Key;
object value = kvp.Value;

You might notice that the value of the Value field is an object. This is because it cannot be strongly typed as integers or strings or even json can be passed in through the URL. Use caution when iterating over the variables because this could lead to a security breach.

When you need to access any data from the URL, the ControllerContext.RouteData provides access to the raw data after the router has executed and mapped the request allowing you to access the current controller and action as well as any of the URL variables.

About the author

By Jamie

My Books