Search code examples
asp.net-mvcsubdomain

ASP.NET MVC Subdomains


I have hosting and domain like that:

www.EXAMPLE.com

I've created few subdomains like that:

www.PAGE1.EXAMPLE.com
www.PAGE2.EXAMPLE.com
www.PAGE3.EXAMPLE.com
... etc...

All of these subdomains point to one and the same ASP.NET MVC 5 Application.

I want to make system which will load data depending of subdomain. Example:

I have Article object which could be a Auto Review or Game review or Book Review etc...

I would like to www.auto.example.com load data where type of article is Auto, to www.book.example.com I would like to load data with type Book etc.

There will be many types of the pages.

What is best practise to do that?

The top level domain www.example.com should display something else. It would be main page for the others.


Solution

  • You can do this by writing a custom Route. Here's how (adapted from Is it possible to make an ASP.NET MVC route based on a subdomain?)

    public class SubdomainRoute : RouteBase
    {
    
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            var host = httpContext.Request.Url.Host;
            var index = host.IndexOf(".");
            string[] segments = httpContext.Request.Url.PathAndQuery.Split('/');
    
            if (index < 0)
                return null;
    
            var subdomain = host.Substring(0, index);
            string controller = (segments.Length > 0) ? segments[0] : "Home";
            string action = (segments.Length > 1) ? segments[1] : "Index";
    
            var routeData = new RouteData(this, new MvcRouteHandler());
            routeData.Values.Add("controller", controller); //Goes to the relevant Controller  class
            routeData.Values.Add("action", action); //Goes to the relevant action method on the specified Controller
            routeData.Values.Add("subdomain", subdomain); //pass subdomain as argument to action method
            return routeData;
        }
    
        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            //Implement your formating Url formating here
            return null;
        }
    }
    

    Add to the route table in Global.asax.cs like this:

    routes.Add(new SubdomainRoute());
    

    And your controller method:

    public ActionResult Index(string subdomain)
    {
        //Query your database for the relevant articles based on subdomain
        var viewmodel = MyRepository.GetArticles(subdomain);
        Return View(viewmodel);
    }