MVC: Accessing the RouteData inside of your C# code 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.

Published on Feb 27, 2019

Tags: ASP.NET MVC and Web API Tutorial | c# | routedata

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.