To implement multi tenant application you have to do some tricks in
C:\Windows\System32\drivers\etc host file
and some coding tricks in App_Start folder at RouteConfig.Csfile by inheriting and implementing IRouteConstraint interface. Also need to see bindings settings in IIS server(for this you need to see the video tutorial provided in below link)
You can get a complete code here https://github.com/ashikcse20/ASP-MVC5-MULTI-TENANT-REPOSITORY with complete written tutorial.
The video tutorial is given here ASP .NET MVC 5 Multi Tenant Example With Basic Code (Single Database Per Tenant)
Code in RouteConfig.Cs at RegisterRoutes function
routes.MapRoute(
name: "Default", url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { TenantRouting = new RoutingConstraint() }
);
Inheriting and implementing IRouteConstraint Interface
public class RoutingConstraint : IRouteConstraint // It is main Class for Multi teanant
{
public bool Match(HttpContextBase httpContext, Route route, string getParameter, RouteValueDictionary values, RouteDirection routeDirection)
{
// Got htis code from http://blog.gaxion.com/2017/05/how-to-implement-multi-tenancy-with.html
var GetAddress = httpContext.Request.Headers["Host"].Split('.');
var tenant = GetAddress[0];
//Here you can apply your tricks and logic. Note for when you put it in public server then www.hamdunsoft.com , www.tenant1.hamdunsoft.com then you need to change a little bit in the conditions . Because a www. was added.
if (GetAddress.Length < 2) // See here for localhost:80 or localhost:9780 ohh also for hamdun soft execution will enter here . But for less than 2? will hamdunsoft.com enter here?
{
tenant = "This is the main domain";
Constant.DatabaseName = "TEST";
if (!values.ContainsKey("tenant"))
values.Add("tenant", tenant);
//return false;
// return true;
}
else if (GetAddress.Length == 2) // execution will enter here for hamdunsoft.com enter here but not for www.hamdunsoft.com
{
tenant = "This is the main domain";
Constant.DatabaseName = GetAddress[0];
if (!values.ContainsKey("tenant"))
values.Add("tenant", tenant);
//return false;
// return true;
}
else if (!values.ContainsKey("tenant")) // for tenant1.hamdunsoft.com execution will enter here
{
values.Add("tenant", tenant);
Constant.DatabaseName = GetAddress[1]+"."+ tenant;
}
return true;
}
}