基于子域到区域的路由,同时保持相同的URL参数

时间:2017-10-10 04:45:35

标签: asp.net-mvc model-view-controller url-routing asp.net-mvc-routing

我尝试在不包含Area参数的情况下路由到基于子域的区域。

我希望能够使用以下路线,例如

example1.domain.com/login

example1.domain.com/landingpage

example2.domain.com/login

example2.domain.com/landingpage

我想让每个子域路由到不同的区域。我已经尝试过这篇文章Is it possible to make an ASP.NET MVC route based on a subdomain?,这导致我http://benjii.me/2015/02/subdomain-routing-in-asp-net-mvc/。但我似乎无法弄清楚如何在URL中没有Area参数。

如何获得我正在寻找的正确网址架构? {subdomain} .domain.com / {action} / {id}

1 个答案:

答案 0 :(得分:2)

要在区域中使用路由,除了执行其他子域路由之外,还需要将DataTokens["area"]参数设置为正确的区域。这是一个例子:

SubdomainRoute

public class SubdomainRoute : Route
{
    // Passing a null subdomain means the route will match any subdomain
    public SubdomainRoute(string subdomain, string url, IRouteHandler routeHandler) 
        : base(url, routeHandler)
    {
        this.Subdomain = subdomain;
    }

    public string Subdomain { get; private set; }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        // A subdomain specified as a query parameter takes precedence over the hostname.
        string subdomain = httpContext.Request.Params["subdomain"]; 
        if (subdomain == null)
        {
            string host = httpContext.Request.Headers["Host"];
            int index = host.IndexOf('.');
            if (index >= 0)
                subdomain = host.Substring(0, index);
        }
        // Check if the subdomain matches this route
        if (this.Subdomain != null && !this.Subdomain.Equals(subdomain, StringComparison.OrdinalIgnoreCase))
            return null;

        var routeData = base.GetRouteData(httpContext);
        if (routeData == null) return null; // The route doesn't match - exit early

        // Store the subdomain as a datatoken in case it is needed elsewhere in the app
        routeData.DataTokens["subdomain"] = subdomain;

        return routeData;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        // Read the current query string and cascade it to the current URL only if it exists
        object subdomainParam = requestContext.HttpContext.Request.Params["subdomain"];
        if (subdomainParam != null)
            values["subdomain"] = subdomainParam;
        return base.GetVirtualPath(requestContext, values);
    }
}

RouteCollectionExtensions

这些扩展方法允许您在应用程序的非区域部分注册路由以使用子域。

public static class RouteCollectionExtensions
{
    public static SubdomainRoute MapSubdomainRoute(
        this RouteCollection routes, 
        string subdomain, 
        string url, 
        object defaults = null, 
        object constraints = null, 
        string[] namespaces = null)
    {
        return MapSubdomainRoute(routes, null, subdomain, url, defaults, constraints, namespaces);
    }

    public static SubdomainRoute MapSubdomainRoute(
        this RouteCollection routes,
        string name,
        string subdomain, 
        string url, 
        object defaults = null, 
        object constraints = null, 
        string[] namespaces = null)
    {
        var route = new SubdomainRoute(subdomain, url, new MvcRouteHandler())
        {
            Defaults = new RouteValueDictionary(defaults),
            Constraints = new RouteValueDictionary(constraints),
            DataTokens = new RouteValueDictionary()
        };
        if ((namespaces != null) && (namespaces.Length > 0))
        {
            route.DataTokens["Namespaces"] = namespaces;
        }
        routes.Add(name, route);
        return route;
    }
}

AreaRegistrationContextExtensions

这些扩展方法允许您注册区域路由以使用子域。

public static class AreaRegistrationContextExtensions
{
    public static SubdomainRoute MapSubdomainRoute(
        this AreaRegistrationContext context, 
        string url, 
        object defaults = null, 
        object constraints = null, 
        string[] namespaces = null)
    {
        return MapSubdomainRoute(context, null, url, defaults, constraints, namespaces);
    }

    public static SubdomainRoute MapSubdomainRoute(
        this AreaRegistrationContext context, 
        string name, 
        string url, 
        object defaults = null, 
        object constraints = null, 
        string[] namespaces = null)
    {
        if ((namespaces == null) && (context.Namespaces != null))
        {
            namespaces = context.Namespaces.ToArray<string>();
        }
        var route = context.Routes.MapSubdomainRoute(name, 
            context.AreaName, url, defaults, constraints, namespaces);
        bool flag = (namespaces == null) || (namespaces.Length == 0);
        route.DataTokens["UseNamespaceFallback"] = flag;
        route.DataTokens["area"] = context.AreaName;
        return route;
    }
}

用法

要使网址格式{subdomain}.domain.com/{action}/{id}使用特定的特定区域,您只需将其注册为AreaRegistration的一部分。

public class AppleAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Apple";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapSubdomainRoute(
            url: "{action}/{id}", 
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }
}
  

注意:您的示例网址有一个限制,即每个区域只能使用一个控制器。 controller是必需的路由值,因此您需要在URL({controller}/{action}/{id})中提供它,或者将其默认为上面的示例 - 后一种情况意味着您只能拥有1个控制器。

当然,您还需要设置DNS服务器以使用子域。