Return to Snippet

Revision: 22875
at January 25, 2010 08:43 by jmcd


Initial Code
public static class LowercaseRouteExtensions
{
    public static Route MapRouteLowercase(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces)
    {
        if (routes == null)
        {
            throw new ArgumentNullException("routes");
        }
        if (url == null)
        {
            throw new ArgumentNullException("url");
        }

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

        if ((namespaces != null) && (namespaces.Length > 0))
        {
            route.DataTokens["Namespaces"] = namespaces;
        }

        routes.Add(name, route);

        return route;
    }

    public static Route MapRouteLowercase(this AreaRegistrationContext @this, string name, string url, object defaults, object constraints, string[] namespaces)
    {
        if (namespaces == null && @this.Namespaces != null)
        {
            namespaces = @this.Namespaces.ToArray();
        }

        var route = @this.Routes.MapRouteLowercase(name, url, defaults, constraints, namespaces);
        route.DataTokens["area"] = @this.AreaName;

        var useNamespaceFallback = (namespaces == null || namespaces.Length == 0);
        route.DataTokens["UseNamespaceFallback"] = useNamespaceFallback;

        return route;
    }
}

public class LowercaseRoute : 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)
    {
        var path = base.GetVirtualPath(requestContext, values);

        if (path != null)
            path.VirtualPath = path.VirtualPath.ToLowerInvariant();

        return path;
    }
}

Initial URL

                                

Initial Description
Use it on your AreaRegistrationContext via the extension MapRouteLowercase

Initial Title
Lowercase Area Routes in ASP.NET MVC2

Initial Tags
aspnet

Initial Language
C#