Tag Archives: SubDomain

Code

Asp.Net MVC 2 Routing SubDomains to Areas

I’ve been building an Asp.Net MVC 2 site with Tom on the new Thap site and we hit a stumbling point regarding sub-domains and areas; you can probably guess what the problem was from the title.

Any way after a bit of googling it looks like no one has figured this out, or that they arn’t sharing. So it’s time I shared the solution that worked for us. This requires no libraries or esoteric settings or anything like that, just a little bit of code that will end up making your routes look like this:

context.Routes.MapSubDomainRoute(
        "Admin_default", // Name
        "admin", // SubDomain
        "{controller}/{action}/{id}", // Url
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Defaults
        new[] { typeof(Controllers.HomeController).Namespace }); // Namespace

First we need to create a Route class that can handle subdomains, lucky for you I just happen to have one. What this class does is check the incoming request, if the sub-domain matches it then checks to see if the rest of the url matches the route you specified:

Update: Since publishing this post I’ve added an update to the code. The GetVirtualPath function ¬†has been overridden to check if the area of the value matches the sub-domain . This was needed because it messed up the url generation for¬†everything.

namespace Your.App
{
  using System.Web;
  using System.Web.Routing;

  /// <summary>
  /// A route class to work with a specific subDomain
  /// </summary>
  public class SubDomainRoute : Route
  {
    /// <summary>
    /// The subDomain to route against
    /// </summary>
    private readonly string subDomain;

    /// <summary>
    /// Initializes a new instance of the <see cref="SubDomainRoute"/> class.
    /// </summary>
    /// <param name="subDomain">The sub domain.</param>
    /// <param name="url">The URL.</param>
    /// <param name="routeHandler">The route handler.</param>
    public SubDomainRoute(string subDomain, string url, IRouteHandler routeHandler) : base(url, routeHandler)
    {
      this.subDomain = subDomain.ToLower();
    }

    /// <summary>
    /// Returns information about the requested route.
    /// </summary>
    /// <param name="httpContext">An object that encapsulates information about the HTTP request.</param>
    /// <returns>
    /// An object that contains the values from the route definition.
    /// </returns>
    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
      var url = httpContext.Request.Headers["HOST"];
      var index = url.IndexOf(".");

      if (index < 0)
      {
        return null;
      }

      var possibleSubDomain = url.Substring(0, index).ToLower();

      if (possibleSubDomain == subDomain)
      {
        var result =  base.GetRouteData(httpContext);
        return result;
      }

      return null;
    }

    /// <summary>
    /// Returns information about the URL that is associated with the route.
    /// </summary>
    /// <param name="requestContext">An object that encapsulates information about the requested route.</param>
    /// <param name="values">An object that contains the parameters for a route.</param>
    /// <returns>
    /// An object that contains information about the URL that is associated with the route.
    /// </returns>
    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
      // Checks if the area to generate the route against is this same as the subdomain
      // If so we remove the area value so it won't be added to the URL as a query parameter
      if(values != null && values.ContainsKey("Area"))
      {
        if(values["Area"].ToString().ToLower() == this.subDomain)
        {
          values.Remove("Area");
          return base.GetVirtualPath(requestContext, values);
        }
      }

      return null;
    }
  }
}

The next step we take is to create a bunch of extensions methods to make mapping the sub-domain a bit easier. I lifted this code straight from the MVC source and made a tiny adjustment.

namespace Your.App
{
  using System;
  using System.Diagnostics.CodeAnalysis;
  using System.Web.Mvc;
  using System.Web.Routing;

  public static class RouteCollectionExtensions
  {
    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, null /* defaults */, (object)null /* constraints */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, defaults, (object)null /* constraints */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults, object constraints)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, defaults, constraints, null /* namespaces */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, string[] namespaces)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, null /* defaults */, null /* constraints */, namespaces);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults, string[] namespaces)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, defaults, null /* constraints */, namespaces);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults, object constraints, string[] namespaces)
    {
      if (routes == null)
      {
        throw new ArgumentNullException("routes");
      }
      if (url == null)
      {
        throw new ArgumentNullException("url");
      }
      if (subDomain == null)
      {
        throw new ArgumentNullException("subDomain");
      }

      Route route = new SubDomainRoute(subDomain, url, new MvcRouteHandler())
      {
        Defaults = new RouteValueDictionary(defaults),
        Constraints = new RouteValueDictionary(constraints)
      };

      if ((namespaces != null) && (namespaces.Length > 0))
      {
        route.DataTokens = new RouteValueDictionary();
        route.DataTokens["Namespaces"] = namespaces;
      }

      routes.Add(name, route);

      return route;
    }
  }
}

The final thing to do is set up your routes in the AreaRegistration class

context.Routes.MapSubDomainRoute(
        "Admin_default", // Name
        "admin", // SubDomain
        "{controller}/{action}/{id}", // Url
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Defaults
        new[] { typeof(Controllers.HomeController).Namespace }); // Namespace

Look familiar?

The namespace section is used to distinguish between Identically name controllers, so if you have a home controller in two areas that line will stop any conflicts.

There is one last item to take note of, when you create a new action in a controller of an area you’ll need to specify the location of the view. If your using the MvcContrib like we do then the T4MVC template comes in vary handy. All the Actions in the areas now look something like this:

    public virtual ActionResult Index()
        {
            return View(this.Views.Index);
        }

Or if you’re not using the T4MVC then this:

    public virtual ActionResult Index()
        {
            return View("~/Areas/Admin/Views/Home/Index.aspx");
        }