【问题标题】:ASP.NET route to mvc or api by subdomainASP.NET 按子域路由到 mvc 或 api
【发布时间】: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


    【解决方案1】:

    这是一篇博客文章,旨在做您正在谈论的事情。本质上,这个想法是在你定义的路由中定义子域:

    http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx

    但是,最简单和最明显的方法是简单地创建两个不同的站点。因为,一个是您的网站,一个是您的 API,因此将它们分成不同的项目是有意义的。

    【讨论】:

    • 同意。需要两个独立项目的明确案例。然而,就其价值而言,AttributeRouting (attributerouting.net) 也支持子域。
    • 我同意你说我应该把它分成 2 个站点,但我现在不能这样做。您的链接对我没有多大帮助,因为它仅路由 mvc 控制器。
    • 2 个站点意味着双重部署和有问题的数据库迁移。所以不绝对不是“最简单的”
    【解决方案2】:

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

    这个网站给了我线索: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
                    );
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 1970-01-01
      • 2011-03-06
      • 2011-03-17
      • 2018-05-20
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 2010-12-09
      相关资源
      最近更新 更多