获取服务器根域名

    public bool IsNumeric(string str)
    {
        
try { int i = Convert.ToInt32(str); return true; }
        
catch { return false; }
    }


    
/// <summary>
    
/// 获取服务器根域名
    
/// </summary>
    
/// <returns></returns>
    public string GetServerDomain()
    {
        
string strHostName = HttpContext.Current.Request.Url.Host.ToString().ToLower(); // 此处获取值转换为小写
        if (strHostName.IndexOf('.'> 0)
        {
            
string[] strArr = strHostName.Split('.');
            
string lastStr = strArr.GetValue(strArr.Length - 1).ToString();
            
if (IsNumeric(lastStr)) // 如果最后一位是数字,那么说明是IP地址
            {
                
return strHostName.Replace("."""); // 替换.为纯数字输出
            }
            
else // 否则为域名
            {
                
string[] domainRules = ".com.cn|.net.cn|.org.cn|.gov.cn|.com|.net|.cn|.org|.cc|.me|.tel|.mobi|.asia|.biz|.info|.name|.tv|.hk|.公司|.中国|.网络".Split('|');
                
string findStr = string.Empty;
                
string replaceStr = string.Empty;
                
string returnStr = string.Empty;
                
for (int i = 0; i < domainRules.Length; i++)
                {
                    
if (strHostName.EndsWith(domainRules[i].ToLower())) // 如果最后有找到匹配项
                    {
                        findStr 
= domainRules[i].ToString(); // www.px915.COM
                        replaceStr = strHostName.Replace(findStr, ""); // 将匹配项替换为空,便于再次判断
                        if (replaceStr.IndexOf('.'> 0// 存在二级域名或者三级,比如:www.px915
                        {
                            
string[] replaceArr = replaceStr.Split('.'); // www px915
                            returnStr = replaceArr.GetValue(replaceArr.Length - 1).ToString() + findStr;
                            
return returnStr;
                        }
                        
else // px915
                        {
                            returnStr 
= replaceStr + findStr; // 连接起来输出为:px915.com
                            return returnStr;
                        };
                    }
                    
else
                    { 
                        returnStr 
= strHostName; 
                    }
                }
                
return returnStr;
            }
        }
        
else
        {
            
return strHostName;
        }
    }
原文地址:https://www.cnblogs.com/wangpei/p/1548733.html