ASP.NET Web Api 2 - Subdomain Attribute Routing

爱⌒轻易说出口 提交于 2019-12-03 22:07:14

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"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!