I've been using AttributeRouting for quite some time in my MVC application. However, one thing it always lacked is subdomain routing in Web Api (among other features in that library that work with MVC but not Web Api).
Now I just read about the new improvements in Web Api regarding Attribute Routing and that it's now included with Web Api out of the box.
However, I see no mention of subdomain routing. Is it supported in Web Api 2?
If not, how can I get subdomain routing in my Web Api so that I can hit the ApiController using http://api.mydomain.com/cars/1
?
Routing is normally used for the portion of the URL after the domain/port. As long as you have your host configured to let Web API handle requests for a domain, you should be able to route URLs within that domain.
If you do want routing to be domain-specific (such as only have requests to the api.mydomain.com domain handled by a certain route), you can use a custom route constraint. To do that with attribute routing, I think you'd need to have:
First, The custom route constraint class itself. See http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-custom-route-constraint-cs for an MVC domain example; the Web API interface is slightly different (http://msdn.microsoft.com/en-us/library/system.web.http.routing.ihttprouteconstraint(v=vs.108).aspx).
Second, A custom route builder. Derive from HttpRouteBuilder and override the BuildHttpRoute method to add your constraint. Something like this:
public class DomainHttpRouteBuilder : HttpRouteBuilder
{
private readonly string _domain;
public DomainHttpRouteBuilder(string domain) { _domain = domain; }
public override IHttpRoute BuildHttpRoute(string routeTemplate, IEnumerable<HttpMethod> httpMethods, string controllerName, string actionName)
{
IHttpRoute route = base.BuildHttpRoute(routeTemplate, httpMethods, controllerName, actionName);
route.Constraints.Add("Domain", new DomainConstraint(_domain));
return route;
}
}
Third, When mapping attribute routes, use your custom route builder (call the overload that takes a route builder):
config.MapHttpAttributeRoutes(new DomainHttpRouteBuilder("api.mydomain.com"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With