获取当前域名的根域C#asp.net
/// <summary>
/// 获取当前域名的根域
/// </summary>
/// <param name="url">域名地址</param>
/// <returns></returns>
public static string RootDomain(string url)
{
if (!url.StartsWith("http://") && !url.StartsWith("https://"))
{
url = "http://" + url;
}
var uri = new Uri(url);
string rootDomain;
switch (uri.HostNameType)
{
case UriHostNameType.Dns:
{
if (uri.IsLoopback)
{
rootDomain = uri.Host;
}
else
{
string host = uri.Host;
var hosts = host.Split('.');
rootDomain = hosts.Length == 2 ? host : string.Format("{0}.{1}", hosts[1], hosts[2]);
}
}
break;
default:
rootDomain = uri.Host;
break;
}
return rootDomain;
}