Thursday, March 31, 2016

MVC - Domain Route for Multi tenancy application to handle different URL

In some cases, we should handle Multi-tenant application with single code base and different domain URLs.

So how do we handle that in MVC Routing?

We have got "Constraints" concept in MVC routing, this is very helpful to filter URL based on domain also.

Okay, let us consider we have different URLs for same code base  for ex:  CompanyAName.com, CompanyBName.com. So here we have to handle two different domain URLs considering URLs already configured for same application.

routes.MapRoute(
    name: "CompanyARoute",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Index", action = "Home", id = UrlParameter.Optional },
    constraints: new { host = "CompanyAName.com" });


routes.MapRoute(
    name: "CompanyBRoute",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Index", action = "Home", id = UrlParameter.Optional },

    constraints: new { host = "CompanyBName.com" });



This code will handle two different domains, "host" in constraints is default syntax and will map to domain automatically. here we can change default Controller, Action to anything or even we can pass some parameters. 


Suppose, if we want to add some subdomain as companyname. For ex;   DefaultURL.com/CompanyName

We can use same "Constraints" to handle this

  routes.MapRoute(
    name: "SubRoute",
    url: "{companyName}/{controller}/{action}/{id}",
    defaults: new { controller = "Index", action = "Home", id = UrlParameter.Optional },
    constraints: new { companyName = "CompanyA" });


To handle multiple company names we can create more routing same like this or even in companyName we can add more like "(CompanyA|CompanyB)". "companyName" in constraints mapped to {companyName} in url.


We can utilize IRouteConstraint interface to extend each constraints attributes.

routes.MapRoute(
  name: "ConstraintRoute,
  url: "{controller}/{action}/{id}",
  defaults: new { controller = "Index", action = "Home", id = UrlParameter.Optional },
  constraints: new { host = new HostRouteConstraint("CompanyAName.com") });

"HostRouteConstraint" is a class extended from IRouteConstraint

using System.Web.Routing;
public class HostRouteConstraint : IRouteConstraint
    {
        private readonly string _host;

        public DomainConstraint(string host)
        {
            _host = host.ToLower();
        }

        public bool Match(HttpContextBase httpContext,
            System.Web.Routing.Route route,
            string parameterName,
            RouteValueDictionary values,
            RouteDirection routeDirection)
        {
//Here you can do your custom logic to match host
            return httpContext.Request.Url.AbsoluteUri.ToLower().Contains(_host);
        }
    }