• mvc3实现用户自定义二级域名


    第一个代码文件

    View Code
     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)
    {
    // 构造 regex
    domainRegex = CreateRegex(Domain);
    pathRegex = CreateRegex(Url);

    // 请求信息
    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 domainMatch = domainRegex.Match(requestDomain);
    Match pathMatch = pathRegex.Match(requestPath);

    // 路由数据
    RouteData data = null;
    if (domainMatch.Success && pathMatch.Success)
    {
    data = new RouteData(this, RouteHandler);

    // 添加默认选项
    if (Defaults != null)
    {
    foreach (KeyValuePair<string, object> item in Defaults)
    {
    data.Values[item.Key] = item.Value;
    }
    }

    // 匹配域名路由
    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;
    }
    }
    }
    }

    // 匹配域名路径
    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)
    {
    // 获得主机名
    string hostname = Domain;
    foreach (KeyValuePair<string, object> pair in values)
    {
    hostname = hostname.Replace("{" + pair.Key + "}", pair.Value.ToString());
    }

    // Return 域名数据
    return new DomainData
    {
    Protocol = "http",
    HostName = hostname,
    Fragment = ""
    };
    }

    private Regex CreateRegex(string source)
    {
    // 替换
    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)
    {
    Regex 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;
    }
    }

    第二个代码文件

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

    在global里注册实现

                routes.Add("DomainRoute", new DomainRoute(
    "{subdomain}.您的域名.com", // Domain with parameters
    "{controller}/{action}/{id}", // URL with parameters
    new { subdomain = "", controller = "Home", action = "Index", id = "" } // Parameter defaults
    ));


    在HomeController的index 里获取域名值

                //获取二级域名
    var subdomain = RouteData.Values["subdomain"].ToString();

    剩下的工作接着做



  • 相关阅读:
    nodejs 文件路径问题
    nodejs
    return , return true , return false的区别
    严防个人极端案事件 中央政法委要求健全危机干预机制
    《资本论》:什么是“原始积累”?农民的土地因何被社会剥夺
    程序员自我修炼(四)—— 代码重构
    中国各民族人口总数排名
    农村人可以去别的村买宅基地吗?这样合不合法?看完你就知道了!
    如果所在的农村拆迁了,可以在另外一个村申请宅基地吗?
    哈姆扎&#183;本&#183;拉登为什么反对美国?
  • 原文地址:https://www.cnblogs.com/jqbird/p/2373304.html
Copyright © 2020-2023  润新知