Wednesday, March 28, 2012

a much better way to do longtail link routing in ASP.MVC (disregard my other post from last night)

The first thing that went through my head this morning was how stupid and embarrassing this post is. A better way to skin the cat I was trying to skin, without any .htaccess nonsense, is to have two routes like this:

public static void RegisterRoutes(RouteCollection routes)
{
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
   
   routes.MapRoute(
      "longtaillinks", "{id}",
      new { controller = "Home", action = "Longtail", id = UrlParameter.Optional },
      new { id = @"([A-Za-z0-9-]+).html" });
   
   routes.MapRoute(
      "Default",
      "{controller}/{action}/{id}",
      new { controller = "Home", action = "Index", id = UrlParameter.Optional }
   );
}

 
 

That which does not fall over to the default route would routed by the first route to the Longtail action which could start off like this:

public ActionResult Longtail(string id)
{
   string[] longtailSegments = id.Replace(".html", "").Split("-".ToCharArray());
   
more code to follow...

 
 

This works! http://www.example.com/foo-bar-baz.html gets consumed as I expected and longtailSegments ends up with three strings containing "foo","bar", and "baz." Further into the Longtail action, logic for what to do with the segments could be offered or called from a different method.

No comments:

Post a Comment