Thursday 14 June 2012

ASP.NET MVC - Domain specific routes using RouteConstraint

I’ve come across using different routes depending upon the domain that the end user is browsing. That might be different based on language (browsing your “.co.uk” site gets English URLs, browsing “.fr” gets French), or perhaps based on brand. Maybe some functionality on your web site is only available to certain sub-brands. Or perhaps you want to direct users that visit uat.mydomain.com to new functionality so they can test it. All of this becomes possible with a Route Constraint. These are simply used to validate whether a route should match a particular incoming URL.

HostConstraint

To apply this kind of filtering based on the host in the URL (i.e. the domain the user is browsing) is such a simple piece of code;
public class HostConstraint : IRouteConstraint
{
    private readonly Regex _host;
 
    public HostConstraint(string pattern)
    {
        _host = new Regex(pattern, 
                RegexOptions.Compiled | RegexOptions.IgnoreCase);
    }
 
    public bool Match(
        HttpContextBase httpContext, 
        Route route, 
        string parameterName, 
        RouteValueDictionary values, 
        RouteDirection routeDirection)
    {
        return _host.IsMatch(httpContext.Request.Url.Host);
    }
}
You can see this constraint takes a Regular Expression pattern to describe host names that it should match, and simply checks the Url.Host on the current HttpContext for success.

Using HostConstraint

Using our new class is really simple - we add it to an anonymous type in the MapRoute call;
routes.MapRoute(
    "Default_us",
    "ussitemap",
    new { controller = "Home", action = "SiteMap" },
    new { host = new HostConstraint("\\.com$") }
);
 
routes.MapRoute(
    "Default_fr",
    "frenchsitemap",
    new { controller = "Home", action = "SiteMap" },
    new { host = new HostConstraint("\\.fr$") }
);

No comments:

Post a Comment