I’m using following code to get the controller/action information from RouteData
RouteData route = RouteTable.Routes.GetRouteData(httpContext);
string controller = route.GetRequiredString("controller");
string action = route.GetRequiredString("action");
But should I change the string “controller” in case that the route map in Global.asax.cs does not have a part with “controller” as follows:
routes.MapRoute(
"Default", // Route name
"{NOTCONTROLLER}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
Thanks!
No. Your route data will always have “controller” key. If you look at the route:
What gets returned by
RouteTable.Routes.GetRouteDatacomes fromcontroller = "Home", not from"{NOTCONTROLLER}/{action}/{id}". When you register a route, whatever is in braces gets mapped to parameter with the same name in the action, except for{controller}and{action}which specify a controller or an action on the fly. Have a read on MVC routing in more detail here.To play around with routes and to understand how they work, have a play with Phil Haack’s route debugger. It’s invaluable if you are stuck in a situation where you just can’t work out how the route works.