ASP.NET通过子域路由到mvc或api的路由

Zot*_*ote 1 asp.net-mvc asp.net-routing asp.net-mvc-4 asp.net-web-api

我们的应用程序有2个域名(www | api).mydomain.com

如何将请求路由到api.mydomain.com到api控制器和www到mvc控制器?

谢谢

Zot*_*ote 7

我使用约束解决了我的问题.

这个网站给了我线索:http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx

这是我的实施:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的路线:

    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
                );
}
Run Code Online (Sandbox Code Playgroud)