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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 通过子域名到mvc或api的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-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
                );
}

猜你在找的asp.Net相关文章