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
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1182
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?
This doesn’t work when you have at least 1 MVC Area in the project. All Urls (not just the Urls of the Area) are not lowercased anymore! This had to be a bug in the framework. http://stackoverflow.com/questions/13271048/net-4-5-mvc-routecollection-lowercaseurls-breaks-when-using-area