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