Search code examples
asp.net-mvcasp.net-mvc-4asp.net-web-apiasp.net-routing

ASP.NET route to mvc or api by subdomain


Our application have 2 domains (www | api).mydomain.com

How can I route requests to api.mydomain.com to api controllers and www to mvc controllers?

Thank you


Solution

  • I solved my problem using constraints.

    This site gave me the clue: http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx

    And here is my implementation:

    public class SubdomainRouteConstraint : IRouteConstraint
    {
        private readonly string _subdomain;
    
        public SubdomainRouteConstraint(string subdomain)
        {
            _subdomain = subdomain;
        }
    
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            return httpContext.Request.Url != null && httpContext.Request.Url.Host.StartsWith(_subdomain);
        }
    }
    

    And my routes:

        public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    #if !DEBUG
                    ,constraints: new { subdomain = new SubdomainRouteConstraint("www") }
    #endif
                );
            }
    
    
            public static void Register(HttpConfiguration config)
            {
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
    #if DEBUG
                    routeTemplate: "api/{controller}/{id}",
    #else
                    routeTemplate: "{controller}/{id}",
    #endif
                    defaults: new {id = RouteParameter.Optional}
    #if !DEBUG
                    , constraints: new {subdomain = new SubdomainRouteConstraint("api")}
    #endif
                    );
    }