I am having issues getting Web API to work with subdomain-based routes. In short, I am getting to the right controller and method but the data token out of the subdomain is not being picked up by WebAPI.
I have this in my scenario:
contoso.myapp.com
fabrikam.myapp.com
{tenant}.myapp.com
All resolving to the same ApiController and I want to be able to extract the {tenant} token.
I used the code in this article http://blog.maartenballiauw.be/post/2012/06/18/Domain-based-routing-with-ASPNET-Web-API.aspx
But there is something that seem to have changed between the time the article was written and ASP.NET Web Api went out of beta. The code in the article is relying on RouteTable.Routes while on Web API routes are configured through HttpConfiguration.Routes which is an HttpRouteCollection and not the usual RouteCollection (it derives from RouteCollection actually).
So I changed the code to derive from HttpRoute instead of Route. Here is the code:
https://gist.github.com/3766125
I configure a route like this
config.Routes.Add(new HttpDomainRoute(
name: "test",
domain: "{tenant}.myapp.com",
routeTemplate: "test",
defaults: new { controller = "SomeController", action = "Test" }
));
And my requests are routed to the right controller. However, the tenant data token is never filled (if I do this.Request.GetRouteData() I see the controller and action tokens but not tenant). If I put a breakpoint on GetRouteData it is never called.
I tried to follow the code path with reflector and see where GetRouteData is being called at the HttpRouteCollection level, but it seems that the collection is enumarating is empty. Not sure exactly how the integration between regular ASP.NET routing and WEb API routing is bridged but it is confusing me.
Any ideas?
The workaround I am using for now is calling explicitly GetRouteData over the Route
this.Request.GetRouteData().Route.GetRouteData(this.Request.RequestUri.ToString(), this.Request)
After thinking of this more, I have a workaround for you. The basic idea of the workaround is to use a route that derives from Route and add it to the RouteCollection directly. That way, the route we are passing will no longer be wrapped inside HttpWebRoute.
The RouteByPassing handler is to workaround another known issue. Hope this helps.
}