The other day I finally had a few minutes to catch up on some blog reading and I came across some interesting posts. I was reading Aaron Mentele’s post titled “Shorter URLs” and really enjoyed the insights. At the bottom of his post he credits Zeldman with a similar post, both focusing on the potential pitfalls and frustrations with URL shortening. I haven’t had many bad experiences with shortened URL’s but I see the potential for disaster.
After the reading it got me thinking how I would implement this. Aaron provides a nice solution editing the .htaccess file but that doesn’t help the .NET developer much. The following is my implementation of this behavior in ASP.NET MVC and it’s geared toward easy reuse across other methods and applications if need be…
First, the route to accept the short URL:
routes.MapRoute(
null,
"p/{postID}",
new { controller = "Blog", action = "ShortUrl" },
new { postID = @"\d+" }
);
Second, the custom action filter to redirect the short url.
public class PermanentRedirectAttribute : ActionFilterAttribute { public override void OnResultExecuted(ResultExecutedContext filterContext) { filterContext.HttpContext.Response.StatusCode = 301; } }
Finally, decorate the action method that handles the short route.
[PermanentRedirect] public RedirectToRouteResult ShortUrl(int postID) { return RedirectToAction("Post", postID); }
Although this is a pretty simple process allow me to clarify. I set up a route that will handle a URL like http://domain.com/p/234. The mvc framework will then pass the {postID} portion of the URL to the “ShortURL” action method. That method does a simple redirect to the action method meant to handle post processing, and now with the action filter sets the status code to 301. Now you can decorate any action method with the [PermanentRedirect] filter and get a fully qualified permanent redirection for URL shortness and SEO awesomeness. Pretty simple and a very cool concept.