从 URL 中获取顶级域名(不包括子域名)的方法在 ASP.NET/C# 中是什么?

3
我正在尝试从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等。

我想从子域URL中仅获取example.comwww.example.com。是否有不需要解析就可以实现此功能的方法?如果没有,请给我建议。

请帮助我!谢谢


1
据我所知,.NET没有本地方法来实现这一点。你已经尽可能地使用了.NET自动获取主机(包括协议和子域名)的功能,但你需要自己解析其余部分。恐怕我不知道有任何库可以为你完成这项工作。 - Equalsk
@Equalsk:感谢提供的信息,我可以进行解析,但我正在寻找更好的解决方案,也许不需要解析。但看起来我最终还是得使用解析。 - aadi1295
1个回答

0

一个尝试来做这个的方法,可以覆盖大多数情况,虽然可能不包括所有边缘情况:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接