ASP.NET Domain-based routing

 In some case, you will want to have different routing for different domains, or sub-domains. Maarten Balliauw has already post a solution, but today I would like to share another solution on ASP.NET Domain-Based Routing. The idea is very simple. It works based on RouteData and RouteConstraint interface. It will be simpler than Maarten's solution but it does not support to extract route variable in domain name. This approach simply serve different page depend on the request domain.

At first, you should understand about RouteContraint, which use to validate request parameter. Here we will create a contraint to check for requested domain. Here is the source code:

public class DomainRouteConstraint : IRouteConstraint
{
#region IRouteConstraint Members

public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
// get hostname without port
string requestDomain = httpContext.Request.Headers["host"].Split(':')[0];
string domain = (string)values["domain"];

return !String.IsNullOrEmpty(domain) && domain.Equals(requestDomain);
}

#endregion
}

The class simply get host name from request header and check it with domain parameter in RouteData. So, later, if we want to create a domain-restricted route, we simply add domain parameter and domain contraint:

// custom domain route
routes.Add("Domain1", new Route("{controller}/{action}/{id}", handler)
{
Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "", domain = "customdomain.com" }),
Constraints = new RouteValueDictionary(new { domain = new DomainRouteConstraint() }),
});

Everything should work like before, nothing changes except the route only match on specified domain. If you want to generate a route for specified domain, just pass domain as URL parameter. And if you want to generate absolute URL with domain name, you will have to write your custom method. Check it here, I leave this part for you so you can understand how this solution work. Let hope this post will be useful for you, or anyone else.

Comments

Works for me. Thanks :)

Where is publishing date in your post? :)

Add new comment