Force MVC Route URL to Lowercase
So one of my pet peeves in web development is mixed case URL’s. And I usually make sure that all my URL’s in my personal projects follow this standard. I also believe, contrary to my URL case standard, that my code should follow standards .NET naming techniques, such as Pascal casing for my method names.
These two naming standards come in to conflict with MVC because the name of the action method in the controller is used in its native Pascal case. Which generates URL’s that look like this:
/Home/Index
/Home/About
However I want them to be generated like this:
/home/index
/home/about
So I developed my own Route based off of the System.Web.Routing.Route to force everything to lowercase.
public class LowercaseRoute : System.Web.Routing.Route
{
public LowercaseRoute(string url, IRouteHandler routeHandler)
: base(url, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
: base(url, defaults, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler)
: base(url, defaults, constraints, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler)
: base(url, defaults, constraints, dataTokens, routeHandler) { }
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
VirtualPathData path = base.GetVirtualPath(requestContext, values);
if (path != null)
path.VirtualPath = path.VirtualPath.ToLowerInvariant();
return path;
}
}
For anybody as anal as me about stupid stuff such as casing of URL’s you should find this class up above a welcomed addition to your MVC projects.
Social: |
| View blog reactions









March 31st, 2008 at 2:46 pm
Force MVC Route URL to Lowercase…
You’ve been kicked (a good thing) - Trackback from DotNetKicks.com…
April 4th, 2008 at 6:52 am
I really hadn’t tought about that one, but I completely agree about correctly casing the URLs. Thanks for sharing the code.
April 7th, 2008 at 11:59 am
[...] Force MVC Route URL to Lowercase [...]
April 13th, 2008 at 12:05 pm
[...] I did a whole post on why I needed this in my toolkit. Mostly because of my obsessions to have all URL’s in [...]
May 15th, 2008 at 7:20 am
[...] I fall on the side of lowercase letters and hyphens splitting the words: [...]
May 31st, 2008 at 11:12 am
[...] Nick Berardi posted a really simple solution. He derived from System.Web.Routing.Route and overrode the GetVirtualPath [...]