Makiwa

Stuart Campbell’s occasional musings about software development, etc.

Lowercase ASP.NET Route URLs

ASP.NET routes are super cool, but if you follow the Pascal naming convention for your server-side class names you end up with ugly mixed case URLs. Maybe it’s just taste, but I prefer them all lower case.

Luckily, Nick Berardi posted a really simple solution. He derived from System.Web.Routing.Route and overrode the GetVirtualPath method.

All I needed to do was add another extension method to the RouteCollection class and I could use it like the original MapRoute method.

 image

Here is the code.

    public static class RouteCollectionExtensions
    {
        public static void MapRouteLowercase(this RouteCollection routes, string name, string url, object defaults)
        {
            routes.MapRouteLowercase(name, url, defaults, null);
        }

        public static void MapRouteLowercase(this RouteCollection routes, string name, string url, object defaults, object constraints)
        {
            if (routes == null)
                throw new ArgumentNullException("routes");

            if (url == null)
                throw new ArgumentNullException("url");

            var route = new LowercaseRoute(url, new MvcRouteHandler())
                            {
                                Defaults = new RouteValueDictionary(defaults),
                                Constraints = new RouteValueDictionary(constraints)
                            };

            if (String.IsNullOrEmpty(name))
                routes.Add(route);
            else
                routes.Add(name, route);
        }
    }

Categorized as Development/ASP.NET, Development

Leave a Reply