加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 通过子域名到mvc或api的ASP.NET路由

发布时间:2020-12-16 00:03:04 所属栏目:asp.Net 来源:网络整理
导读:我们的应用程序有2个域名(www | api).mydomain.com 如何将请求路由到api.mydomain.com到api控制器和www到mvc控制器? 谢谢 解决方法 我使用约束解决了我的问题. 这个网站给了我线索:http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-creat
我们的应用程序有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
                );
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读