从asp.net / c#中的url(不含子域名)获取顶级域名

本文关键字:域名 获取 net asp url 中的 | 更新日期: 2023-09-27 18:02:50

我正试图从URL获得根域名,到目前为止,我使用的是Request.Url.AuthorityRequest.Url.Host,两者都工作良好的URL没有子域。例如

URL: http://www.example.com以上两个方法都返回www.example.com

但是如果URL中有子域,它们也会返回子域。例如,从http://sub.example.com返回sub.example.com,从http://sub.sub.example.com返回sub.sub.example.com,以此类推。

我想得到只是example.comwww.example.com甚至从子域URL。有没有办法不解析就得到这个?或者不,请给我一些建议。

请帮帮我!由于

从asp.net / c#中的url(不含子域名)获取顶级域名

尝试这样做,将涵盖大多数情况,尽管可能不是所有的边缘情况:

using System;
using System.Linq;
public class Program
{
    static public string GetHostnameWithoutSubdomain(string url)
    {
        Uri uri = new Uri(url);
        if (uri.ToString().Contains("localhost"))
        {
            return uri.Authority;
        }
        string[] uriParts = uri.Host.Split('.');
        int lastIndex = uriParts.Length - 1;
        // Ensure that the URI isn't an IP address by checking whether the last part is a number or (as it should be) a top-level domain:
        if (uriParts[uriParts.Length - 1].All(char.IsDigit))
        {
            return uri.Host;
        }
        // If the URI has more than 3 parts and the last part has just two characters, e.g. "uk" in example.co.uk or "cn" in moh.gov.cn, it's probably a top-level domain:
        if (uriParts.Length > 3 && uriParts[lastIndex].Length <= 2)
        {
            return uriParts[lastIndex - 2] + "." + uriParts[lastIndex - 1] + "." + uriParts[lastIndex];
        }
        if (uriParts.Length > 2)
        {
            return uriParts[lastIndex - 1] + "." + uriParts[lastIndex];
        }
        return uri.Host;
    }
    public static void Main()
    {
        Console.WriteLine(GetHostnameWithoutSubdomain("https://localhost:123/some/page"));
        Console.WriteLine(GetHostnameWithoutSubdomain("https://example.com/some/page"));
        Console.WriteLine(GetHostnameWithoutSubdomain("https://www.example.com/some/page"));
        Console.WriteLine(GetHostnameWithoutSubdomain("https://test.www.example.com/some/page"));
        Console.WriteLine(GetHostnameWithoutSubdomain("https://255.255.255.255/some/page"));
        Console.WriteLine(GetHostnameWithoutSubdomain("https://test.www.example.co.uk/some/page"));
        Console.WriteLine(GetHostnameWithoutSubdomain("https://www.moh.gov.cn/some/page"));
    }
}

这也适用于具有不同于生产域的测试环境的开发设置,因此处理localhost边缘情况。

输出:

localhost:123
example.com
example.com
example.com
255.255.255.255
example.co.uk
moh.gov.cn