RouteCollection.LowercaseUrls .Net 4.5

It’s such a good feeling to reduce code. Previously I’ve been using some custom code to get lower case routes in my ASP.Net MVC apps. There’s also a NuGet package for it. But if your ASP.Net MVC site runs on .Net 4.5, there’s now a much simpler way:

routes.LowercaseUrls = true;

Away goes this old code (thanks to @leedumond) which has the code on CodePlex:

public class LowerCaseRoute : Route
{
    //Constructors removed for clarity

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        var path = base.GetVirtualPath(requestContext, values);

        if (path != null)
        {
            var virtualPath = path.VirtualPath;
            var indexOf = virtualPath.IndexOf("?");

            if (indexOf > 0)
            {
                var leftPart = virtualPath.Substring(0, indexOf).ToLowerInvariant();
                var queryPart = virtualPath.Substring(indexOf);
                path.VirtualPath = string.Concat(leftPart, queryPart);
            }
            else
                path.VirtualPath = path.VirtualPath.ToLowerInvariant();
        }

        return path;
    }
}

and the extension method

public static class RouteExtensions
{
    public static Route MapLowerCaseRoute(this RouteCollection routes, string name, string url, object defaults)
    {
        var defaultDictionary = defaults == null
            ? new RouteValueDictionary()
            : new RouteValueDictionary(defaults);

        var route = new LowerCaseRoute(url, defaultDictionary, new MvcRouteHandler());

        if (string.IsNullOrWhiteSpace(name))
            routes.Add(route);
        else
            routes.Add(name, route);

        return route;
    }
}

Yet another step taken to reduce the code base.

//Daniel

About these ads

3 thoughts on “RouteCollection.LowercaseUrls .Net 4.5

  1. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1182

  2. This looks great but it appears to break from the moment you use AreaRegistrationContext.MapRoute. All Urls will not be lowercase anymore! not only Urls to your Area. Any ideas?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s