1

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

Zote
  • 5,343
  • 5
  • 41
  • 43

2 Answers2

7

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
                );
}
Zote
  • 5,343
  • 5
  • 41
  • 43
1

Here is a blog post that aims at doing just what you are talking about. Essentially, the idea is to define the sub-domain in the routes you define:

http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx

However, the easiest and most obvious approach is to simply create two different sites. Since, one is your website and one is your API it make sense to seperate them into different projects.

marteljn
  • 6,446
  • 3
  • 30
  • 43
  • Agreed. Clear-cut case of needing two separate projects. However, for what it's worth, AttributeRouting (http://attributerouting.net/) has subdomain support as well. – Chris Pratt Mar 05 '13 at 21:23
  • I agree when you say that I should split it in 2 sites, but I can't do it now. You link doesn't help me alot, since it is routing only mvc controllers. – Zote Mar 05 '13 at 21:45
  • 1
    2 sites mean double deployment and problematic db migrations. So no definitely not the "easiest" – Kugel Feb 27 '14 at 00:35