notes from a passionate developer





This is a personal blog. The opinions expressed here represent my own and not those of my employer, nor current or previous. All content is published "as is", without warranty of any kind and I don't take any responsibility and can't be liable for any claims, damages or other liabilities that might be caused by the content.

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)
                var queryPart = virtualPath.Substring(indexOf);
                path.VirtualPath = string.Concat(leftPart, queryPart);
                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(
            new MvcRouteHandler());

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

        return route;

Yet another step taken to reduce the code base.


View Comments