I started rolling up the older blog posts into archive. While doing so, I learned a valuable lesson about routing. We have to put the most specific route first and most general last.
It is very easy to make mistake here. If you do up the entire routing and older links start either looking funky or worse end up breaking the functionality. The reason is asp.net routing maps the request url to the first matching route entry. It doesn’t go beyond that.
My goal was to achieve the following url for the Archived items
http://mvcdeveloper.net/Blogs/Archives/2012/4
While the individuals still point to my details view as it does from the home page
http://mvcdeveloper.net/Blogs/Details/11/It's-all-about-Metro!
I achieved it by have routes defined as follows:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// put the least greedy route first
// in other words put the least general route first
routes.MapRoute(
"Archives", // Route name
"Blogs/Archives/{year}/{month}", // URL with parameters
new { controller = "BlogItem", action = "Archives", year = 0, month = 0 } // Parameter defaults
);
routes.MapRoute(
"Blog Details", // Route name
"Blogs/{action}/{id}/{slug}", // URL with parameters
new { controller = "BlogItem", action = "Details", id = 0, slug = "" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "BlogItem", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
Notice the order here. The most general route is at the bottom and very specific at the top.
Here's another gotcha!
If you are testing locally and routes don't get picked up, just restart whatever server(ASP.net development server,IIS,etc) you are using and that should take care of it.
Questions? Fire away!
Comments