Possible Duplicate:
Is it possible to make an ASP.NET MVC route based on a subdomain?
In asp.net MVC 3 site i'd like to create online stores for users.
Any store that is created by user should have a URL like "shopname.mydomain.com".
I tried some routing work but failed at all. I am researching for a solution but cannot find any proper solution.
My purpose is that; if I can add a route to manage any request that tries to find a subdomain I will check if it is a user online shop name and get the dynamic data on play.
Need routing help :) Thanks.
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.
You'll need to add a dns entry for *.mydomain.com
to point at the root application, then when handling the request in the root application, check the request host to determine which shopname
is specified.