Friday, February 22, 2013

Using lowercase route URL-s in ASP.NET MVC

I've recently started using ASP.NET MVC again and get to the same problem - pascal case generated URL-s. So URL from MVC looks like example.com/Home/About. This is considered bad for search engine optimization, and is ugly in my opinion. Prior to MVC 4 it was easy to trick URL generation engine and use lowercase controllers and actions in ActionLink helper:

@Html.ActionLink("About", "about", "home")

Code above will generate proper route /home/about. In ASP.NET MVC 4 it is much more easier to achieve this by setting LowercaseUrls property to true in routes initialization.  You do this in App_Start/RoutesConfig.cs file. Here is full code snippet:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.LowercaseUrls = true;

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

This is only available in MVC 4.