I recently got burned by the fact that these two MVC4 routes, apparently, function differently. I was wondering if someone could highlight what’s going on so I could better understand.
routes.MapRoute(
"post-User",
"User",
new { controller = "User", action = "create" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
routes.MapRoute(
"post-User",
"{controller}",
new { controller = "User", action = "create" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
I thought that the {controller} bit was a placeholder and that saying controller = “User” in the next line would make these two statements equivilant. Apparently using {controller} sets up defaults for all routes?
You are correct in your belief that the
{controller}substring acts as a placeholder for a controller name. With that in mind, then, the following route will match any controller, but default to theUsercontroller where no controller is specified:The following, however, will match the route
Userand – because no controller can be specified – will always route to theUsercontroller:In this instance the difference is meaningless because all you’re doing is forcing the route
Userto map to a controllerUser, which is exactly what will happen in your first route anyway.However, consider the following:
Now, your top route will match requests to the
Usercontroller, with an optional action specified and will default toMyDefaultAction. Requests to any other controller will not match the first route – because the route does not begin with the constant stringUser– and will default back to the second route (foo). Again, the action is optional; however, now, unlike the requests to theUsercontroller, your default action for other controllers will be theIndexaction.So now…
.../Userdefaults to theMyDefaultActionaction..../SomeOtherControllerdefaults to theIndexaction.