Named Routes in ASP.NET MVC 3

8 Jun

I’m a recent convert to named routes. Using a named route to create a link or URL gives a you level of explicitness that’s comforting in most situations and a lifesaver in others. In their simplest form, though, named routes lead to DRYer routing and can save you some serious maintenance headaches.

All routes are effectively named routes. Using a named route means to specify the route by name instead of allowing the routing engine to determine which one to use. This means that a route that you intend to reference by name is created the same as any other route:

	name: "Post",
	url: "Post/{id}",
	defaults: new { controller = "Posts", action = "Details", id = UrlParameter.Optional }

If you were to use this as a typical action link, you’d specify the link text, controller, action and any route values (in this case id) as parameters in Html.ActionLink(), like this:

@Html.ActionLink("Show", "Posts", "Details", new { id = 4 })

The downside of this technique is that if you were to change a controller name, change an action name or move an action, your link would break. And not just this link, but any ActionLink that points to that combination of controller and action. The other danger is that you have no guarantees as to which route will be pulled from the routing table. It’s easy to envision a scenario where you have to figure out which of 50 routes in the routing table is being used. With named routes, you avoid both of these problems, and as a side benefit your link code is shorter too. To use a named route link, you only need to specify the link text, the name of the route and any route values as parameters, like this:

@Html.RouteLink("Show", "Post", new { id = 4 })

This link is now protected against future change, takes up a little less space, and leaves no doubts as to which route will be utilized. The one negative is that there is now an extra step to find the action and controller used by the route, but in a sensibly-structured site it shouldn’t take a wild guess to figure it out. In my mind these benefits vastly outweigh the slight obfuscation. With named routes, you’ll always know what you get.

%d bloggers like this: