ASP.NET MVC子域

时间:2013-12-16 11:26:53

标签: asp.net-mvc subdomain

我有这样的托管和域名:

www.EXAMPLE.com

我创建了几个这样的子域名:

www.PAGE1.EXAMPLE.com
www.PAGE2.EXAMPLE.com
www.PAGE3.EXAMPLE.com
... etc...

所有这些子域都指向同一个ASP.NET MVC 5应用程序。

我想制作根据子域加载数据的系统。 例如:

我有文章对象,可以是自动评论或游戏评论或书评等......

我想www.auto.example.com加载文章类型为Auto的数据,到www.book.example.com我想加载类型为Book等的数据。

会有很多类型的网页。

这样做的最佳做法是什么?

顶级域名www.example.com应该显示其他内容。这将是其他人的主页。

3 个答案:

答案 0 :(得分:15)

您可以通过编写自定义路线来完成此操作。这是如何(改编自Is it possible to make an ASP.NET MVC route based on a subdomain?

public class SubdomainRoute : RouteBase
{

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var host = httpContext.Request.Url.Host;
        var index = host.IndexOf(".");
        string[] segments = httpContext.Request.Url.PathAndQuery.Split('/');

        if (index < 0)
            return null;

        var subdomain = host.Substring(0, index);
        string controller = (segments.Length > 0) ? segments[0] : "Home";
        string action = (segments.Length > 1) ? segments[1] : "Index";

        var routeData = new RouteData(this, new MvcRouteHandler());
        routeData.Values.Add("controller", controller); //Goes to the relevant Controller  class
        routeData.Values.Add("action", action); //Goes to the relevant action method on the specified Controller
        routeData.Values.Add("subdomain", subdomain); //pass subdomain as argument to action method
        return routeData;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        //Implement your formating Url formating here
        return null;
    }
}

像这样添加到Global.asax.cs中的路由表:

routes.Add(new SubdomainRoute());

你的控制器方法:

public ActionResult Index(string subdomain)
{
    //Query your database for the relevant articles based on subdomain
    var viewmodel = MyRepository.GetArticles(subdomain);
    Return View(viewmodel);
}

答案 1 :(得分:6)

这是我想用ASP.NET MVC做很长时间的事情,但是......这不是ASP.NET MVC负责的问题。这是服务器问题(IIS)。您需要做的是允许IIS服务器上的通配符子域,并将它们指向一个应用程序。

然后你可以用 HttpContext

做这样的事情
HttpContext.Current.Request.Url.Host // user1.yourwebsite.com

然后你只需解析它并将其推送到你认为合适的ASP.NET MVC应用程序中:

  • 将其推入会话
  • 更新当前路线数据并按
  • 中的值
  • 等...

选择权取决于你。

注意:这方面的缺点是,这会使本地开发变得越来越困难,因此您可能想要在应用程序中模拟一种伪造子域名的方法。

答案 2 :(得分:0)

我尝试Paul Taylor上面的答案非常好,但这对我来说并不完全有效。 我使用Route类的实现。

将您的自定义域添加到C:/Windows/System32/drivers/etc/hosts文件

  • 127.0.0.1 subdomain.localhost.com

DomainData.cs

public class DomainData
{
  public string Protocol { get; set; }
  public string HostName { get; set; }
  public string Fragment { get; set; }
}

DomainRoute.cs

public class DomainRoute : Route
{
  private Regex domainRegex;
  private Regex pathRegex;

  public string Domain { get; set; }

  public DomainRoute(string domain, string url, RouteValueDictionary defaults)
    : base(url, defaults, new MvcRouteHandler())
{
    Domain = domain;
}

public DomainRoute(string domain, string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
    : base(url, defaults, routeHandler)
{
    Domain = domain;
}

public DomainRoute(string domain, string url, object defaults)
    : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
{
    Domain = domain;
}

public DomainRoute(string domain, string url, object defaults, IRouteHandler routeHandler)
    : base(url, new RouteValueDictionary(defaults), routeHandler)
{
    Domain = domain;
}

public override RouteData GetRouteData(HttpContextBase httpContext)
{
    // Build regex
    domainRegex = CreateRegex(Domain);
    pathRegex = CreateRegex(Url);

    // Request information
    string requestDomain = httpContext.Request.Headers["host"];
    if (!string.IsNullOrEmpty(requestDomain))
    {
        if (requestDomain.IndexOf(":") > 0)
        {
            requestDomain = requestDomain.Substring(0, requestDomain.IndexOf(":"));
        }
    }
    else
    {
        requestDomain = httpContext.Request.Url.Host;
    }
    string requestPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) +
                         httpContext.Request.PathInfo;

    // Match domain and route
    Match domainMatch = domainRegex.Match(requestDomain);
    Match pathMatch = pathRegex.Match(requestPath);

    // Route data
    RouteData data = null;
    if (domainMatch.Success && pathMatch.Success && requestDomain.ToLower() != "tg.local" &&
        requestDomain.ToLower() != "tg.terrasynq.net" && requestDomain.ToLower() != "www.townsgossip.com" &&
        requestDomain.ToLower() != "townsgossip.com")
    {
        data = new RouteData(this, RouteHandler);

        // Add defaults first
        if (Defaults != null)
        {
            foreach (KeyValuePair<string, object> item in Defaults)
            {
                data.Values[item.Key] = item.Value;
            }
        }

        // Iterate matching domain groups
        for (int i = 1; i < domainMatch.Groups.Count; i++)
        {
            Group group = domainMatch.Groups[i];
            if (group.Success)
            {
                string key = domainRegex.GroupNameFromNumber(i);

                if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                {
                    if (!string.IsNullOrEmpty(group.Value))
                    {
                        data.Values[key] = group.Value;
                    }
                }
            }
        }

        // Iterate matching path groups
        for (int i = 1; i < pathMatch.Groups.Count; i++)
        {
            Group group = pathMatch.Groups[i];
            if (group.Success)
            {
                string key = pathRegex.GroupNameFromNumber(i);

                if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                {
                    if (!string.IsNullOrEmpty(group.Value))
                    {
                        data.Values[key] = group.Value;
                    }
                }
            }
        }
    }

    return data;
}

public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
    return base.GetVirtualPath(requestContext, RemoveDomainTokens(values));
}

public DomainData GetDomainData(RequestContext requestContext, RouteValueDictionary values)
{
    // Build hostname
    string hostname = Domain;
    foreach (KeyValuePair<string, object> pair in values)
    {
        hostname = hostname.Replace("{" + pair.Key + "}", pair.Value.ToString());
    }

    // Return domain data
    return new DomainData
    {
        Protocol = "http",
        HostName = hostname,
        Fragment = ""
    };
}

private Regex CreateRegex(string source)
{
    // Perform replacements
    source = source.Replace("/", @"\/?");
    source = source.Replace(".", @"\.?");
    source = source.Replace("-", @"\-?");
    source = source.Replace("{", @"(?<");
    source = source.Replace("}", @">([a-zA-Z0-9_\-]*))");

    return new Regex("^" + source + "$");
}

private RouteValueDictionary RemoveDomainTokens(RouteValueDictionary values)
{
    var tokenRegex =
        new Regex(
            @"({[a-zA-Z0-9_\-]*})*\.?\/?({[a-zA-Z0-9_\-]*})*\.?\/?({[a-zA-Z0-9_\-]*})*\.?\/?({[a-zA-Z0-9_\-]*})*\.?\/?({[a-zA-Z0-9_\-]*})*\.?\/?({[a-zA-Z0-9_\-]*})*\.?\/?({[a-zA-Z0-9_\-]*})*\.?\/?({[a-zA-Z0-9_\-]*})*\.?\/?({[a-zA-Z0-9_\-]*})*\.?\/?({[a-zA-Z0-9_\-]*})*\.?\/?({[a-zA-Z0-9_\-]*})*\.?\/?({[a-zA-Z0-9_\-]*})*\.?\/?");
    Match tokenMatch = tokenRegex.Match(Domain);
    for (int i = 0; i < tokenMatch.Groups.Count; i++)
    {
        Group group = tokenMatch.Groups[i];
        if (group.Success)
        {
            string key = group.Value.Replace("{", "").Replace("}", "");
            if (values.ContainsKey(key))
                values.Remove(key);
        }
    }

    return values;
  }
}

参考:http://www.howtobuildsoftware.com/index.php/how-do/UaR/aspnet-mvc-5-domain-routing-in-mvc5