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

yquaqz18  于 2023-05-19  发布在  .NET
关注(0)|答案(1)|浏览(184)

我试图从一个URL获取根域名,到目前为止,我使用的是Request.Url.AuthorityRequest.Url.Host,两者都可以很好地处理没有子域的URL。例如
URL:http://www.example.com以上两种方法都返回www.example.com
但从URL与sudomains在它他们返回子域以及。例如http://sub.example.com,它们返回sub.example.com,从http://sub.sub.example.com,它们返回sub.sub.example.com等等。
我想得到的只是example.comwww.example.com甚至从子域的URL。有没有办法不解析就得到这个?请给我一些建议。
请帮帮我!谢谢

rta7y2nd

rta7y2nd1#

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

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

相关问题