2

I am working on a MVC5 project with Areas. My plan is to publish this one codebase into 3 different IIS web servers. I thought about using the subdomain to route users to the designated application.

  • Server 1 - App1.myweb.com
  • Server 2 - App2.myweb.com
  • Server 3 - App3.myweb.com

Areas (App1, App2, App3)

The subdomain class below gives me the URL subdomain but I do not know how to route traffic to the correct Area.

SubdomainRoute.cs

    public class SubdomainRoute : RouteBase
{
    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        if (httpContext.Request == null || httpContext.Request.Url == null)
        {
            return null;
        }

        var host = httpContext.Request.Url.Host;
        var index = host.IndexOf(".");
        string[] segments = httpContext.Request.Url.PathAndQuery.TrimStart('/').Split('/');

        if (index < 0)
        {
            return null;
        }

        var subdomain = host.Substring(0, index);
        string[] blacklist = { "www", "demo", "mail" };

        if (blacklist.Contains(subdomain))
        {
            return null;
        }

        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);
        routeData.Values.Add("action", action);
        routeData.Values.Add("subdomain", subdomain);

        return routeData;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        return null;
    }
}

RouteConfig.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.Add(new SubdomainRoute());


        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

I found this code from http://benjii.me/2015/02/subdomain-routing-in-asp-net-mvc/ but I need to route to Areas.

How do I use the subdomain value from SubdomainRoute.cs to route to my Areas?

Please advise. Thanks.

1 Answers1

0

Option #1

Add the line:

routeData.DataTokens["area"] = subdomain;

Option #2

Implement IRouteWithArea in your SubdomainRoute and return the value of subdomain in the Area property.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212