我们的应用程序有2个域名(www | api).mydomain.com
如何将请求路由到api.mydomain.com到api控制器和www到mvc控制器?
谢谢
解决方法
我使用约束解决了我的问题.
这个网站给了我线索: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); } }
我的路线:
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 ); }