I have found a very powerful way. So check this :)
First of all for application development server of visual studio you have to edit the 'hosts' file.
Open notepad as administrator. Add any name for your domain something like
127.0.0.1 mydomain.com
127.0.0.1 sub1.mydomain.com
and what you need to use on development.
After give a specific port number to your web project. For example "45499". By this way you will be able to sen request to your project by writing in browser :
mydomain.com:45499
or
sub1.mydomain.com:45499
That was the preparing step. Lets get on the answer.
By using the IRouteConstraint
class you can create your route constrains.
public class SubdomainRouteConstraint : IRouteConstraint
{
private readonly string SubdomainWithDot;
public SubdomainRouteConstraint(string subdomainWithDot)
{
SubdomainWithDot = subdomainWithDot;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var url = httpContext.Request.Headers["HOST"];
var index = url.IndexOf(".");
if (index < 0)
{
return false;
}
//This will bi not enough in real web. Because the domain names will end with ".com",".net"
//so probably there will be a "." in url.So check if the sub is not "yourdomainname" or "www" at runtime.
var sub = url.Split('.')[0];
if(sub == "www" || sub == "yourdomainname" || sub == "mail")
{
return false;
}
//Add a custom parameter named "user". Anything you like :)
values.Add("user", );
return true;
}
}
And add your constrain in any route you would like to use.
routes.MapRoute(
"Sub", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "SubdomainController", action = "AnyActionYouLike", id = UrlParameter.Optional },
new { controller = new SubdomainRouteConstraint("abc.") },
new[] { "MyProjectNameSpace.Controllers" }
);
Put this routes before your default route. That's all.
In the constraint you may do anything like check for subdomain name is a client shop name or whatever.