Routing a subdomain with MVC3
I am wanting to create a service for some of my customers that will allow them to have there own webpage on a MVC3 site I have built.
I want a business to be able to have a url that looks like www.BusinessName.mydomain.com
Is it possible to create a route within MVC3 that will allow me to do this?
Thanks for your help
Ok so I think I have gotten a little further.
Ideally I want to be able to have a wildcard for the subdomain in IIS however from the research I have done it looks like this isn't possible.
I have manually added www.mycompany.mydomain.com into IIS and updated my global.ascx to contain this
public class SubDomainRoute : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var url = httpContext.Request.Headers["HOST"];
var subDomain = Helpers.Helpers.GetSubDomain(url);
if (subDomain==null)
return null;
var routeData = new RouteData(this, new MvcRouteHandler());
switch (subDomain)
{
case "mycompany":
routeData.Values.Add("controller", "SubDomain");
routeData.Values.Add("action", "Index");
break;
default:
routeData.Values.Add("controller", "Home");
routeData.Values.Add("action", "Index");
break;
}
return routeData;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return null;
}
}
So now I can browse www.mycompanyname.mydomain.com and the correct controller is loaded.
I now have 2 problems.开发者_Python百科
If I browse to www.mistake.mydomain.com I get a 502 error. What can I do in IIS to redirect to www.mydomain.com if www.mistake.mydomain.com isn't found?
Once I have browsed to www.mycompanyname.mydomain.com all of the links within my main menu are now pointing to e.g. www.mycompanyname.mydomain.com/contactus which is wrong, how do I ensure the menu items are not using the subdomain within the url?
I'd suggest a slightly different approach - only caveat is that this web site must be the only one on IIS. Because IIS doesn't support wildcard host headers, it has to be Default Web site.
This way, you will get all requests (including www.mistake.mydomain.com) to your application's front door, and you can handle them appropriately.
In your MVC application, don't use routing for subdomains, use Application_BeginRequest. There you do what you have to do with Request.Headers["HOST"] and send them where you want them.
The way I see it, Routes are meant to be used for routing user when he gets to the site, not to decide which site user is visiting...
精彩评论