【发布时间】:2013-02-20 11:14:08
【问题描述】:
我们的应用程序有 2 个域 (www | api).mydomain.com
如何将 api.mydomain.com 的请求路由到 api 控制器,将 www 路由到 mvc 控制器?
谢谢
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-routing
我们的应用程序有 2 个域 (www | api).mydomain.com
如何将 api.mydomain.com 的请求路由到 api 控制器,将 www 路由到 mvc 控制器?
谢谢
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-routing
这是一篇博客文章,旨在做您正在谈论的事情。本质上,这个想法是在你定义的路由中定义子域:
http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx
但是,最简单和最明显的方法是简单地创建两个不同的站点。因为,一个是您的网站,一个是您的 API,因此将它们分成不同的项目是有意义的。
【讨论】:
我使用约束解决了我的问题。
这个网站给了我线索: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
);
}
【讨论】: