Geeks With Blogs

I am rebuilding a site that was originally created on Django in MVC4. The original site used dashes in the URLs to take advantage of hypothetical SEO points. I want to keep as many of the original URLs as possible, so that the site doesn’t lose any relevance advantages that it has gained by its content. A quick search revealed the URL above and a great explanation of how to add a custom RouteHandler that replaces the dashes with underscores. That works great!

I modified the example a little bit because I am trying to replicate URLs like “”. The action in this case is in the controller’s spot. Building upon the example provided in the above URL, here is my custom RouteHandler.

public class MyRouteHandler : MvcRouteHandler
    static private Dictionary<string, string> DashMap = new Dictionary<string,string>() {
        { "about-us", "home" },
        { "contact-us", "home" }

    protected override IHttpHandler GetHttpHandler(RequestContext rc)
        string controller = rc.RouteData.Values["controller"] as string;
        string action = rc.RouteData.Values["action"] as string;
        if (DashMap.ContainsKey(controller))
            action = controller;
            controller = DashMap[controller];

        rc.RouteData.Values["controller"] = controller.Replace("-", "");
        rc.RouteData.Values["action"] = action.Replace("-", "");

        return base.GetHttpHandler(rc);

In the case of “”, the controller will be set to the “about-us” action and the action will be set to “Index” (based on the default route.) My code looks up the controller in the DashMap and if applicable moves the controller value to the action part of the route and sets the controller to the value of the corresponding dictionary item. Then, I remove the dashes because I hate using underscores in method names. Creating a link looks like this:

@Url.Action(“”, “about-us”)

The resulting URL created by the Url helper is “”, which is the exact same as the original url used by the django version of the site. I may have been able to solve this problem by changing the route map; however, I personally think this solution is cleaner.

Posted on Saturday, December 29, 2012 6:52 PM Web | Back to top

Comments on this post: Using Dashes in URLs in MVC4

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © MightyZot | Powered by: