简体   繁体   English

如何从URL获取域名

[英]How to get the domain name from an URL

The goal here is to know if aa given URL is in a given domain. 这里的目标是知道给定的URL是否在给定的域中。

For example, my domain is : www.google.fr I need to know if this : http://token.google.fr/news/something is in the domain 例如,我的域名是:www.google.fr,我需要知道是否: http : //token.google.fr/news/something在该域名中

I have a HashSet of Uri with all URL i need to check and my domain also in a Uri object. 我有一个Uri的HashSet,其中包含我需要检查的所有URL,并且我的域也位于Uri对象中。

Is there a way to do that by manipulating Uri object ? 有没有办法通过操纵Uri对象来做到这一点?

i Have tried to compare both Uri.Authority but since we might have a prefix and / or a suffix, Uri.Compare() is not usable. 我曾尝试比较Uri.Authority但由于我们可能有前缀和/或后缀,因此Uri.Compare()不可用。

You could split the Uri.Authority and check the TLD and Domain Name which should always be the last two elements of the split (assuming it's a valid URL) 您可以拆分Uri.Authority并检查TLD和域名,它们应该始终是拆分的最后两个元素(假设它是有效的URL)

Example

Uri uri1 = new Uri("http://test.google.ca/test/test.html");
Uri uri2 = new Uri("http://google.ca/test/test.html");

string[] uri1Parts = uri1.Authority.Split(new char[] { '.' });
string[] uri2Parts = uri2.Authority.Split(new char[] { '.' });

//Check the TLD and the domain
if (uri1Parts[uri1Parts.Length - 1] == uri2Parts[uri2Parts.Length - 1] && uri1Parts[uri1Parts.Length - 2] == uri2Parts[uri2Parts.Length - 2])
{
    Console.WriteLine(uri1Parts[uri1Parts.Length - 2] + "." + uri1Parts[uri1Parts.Length - 1]);
}

Edit 编辑

If your URIs have ports you'll need to take them into account. 如果您的URI具有端口,则需要考虑它们。 Here's a little better version. 这是一个更好的版本。

public static bool AreSameDomain(Uri uri1, Uri uri2)
{
    string uri1Authority = uri1.Authority;
    string uri2Authority = uri2.Authority;

    //Remove the port if port is specified
    if (uri1Authority.IndexOf(':') >= 0)
    {
        uri1Authority = uri1Authority.Substring(0, uri1Authority.IndexOf(':')); 
    }
    if (uri2Authority.IndexOf(':') >= 0)
    {
        uri2Authority = uri1Authority.Substring(0, uri2Authority.IndexOf(':'));
    }

    string[] uri1Parts = uri1Authority.Split(new char[] { '.' });
    string[] uri2Parts = uri2Authority.Split(new char[] { '.' });

    return (uri1Parts[uri1Parts.Length - 1] == uri2Parts[uri2Parts.Length - 1] //Checks the TLD
        && uri1Parts[uri1Parts.Length - 2] == uri2Parts[uri2Parts.Length - 2]); //Checks the Domain Name
}

I could be totally misunderstanding what you are trying to do, but would this be useful: 我可能完全误解了您要做什么,但这会很有用:

Uri u1 = new Uri("http://token.google.fr/news/something");
Uri u2 = new Uri("http://www.google.fr");

string domain1 = u1.Authority.Substring(u1.Authority.IndexOf('.') + 1);
string domain2 = u2.Authority.Substring(u2.Authority.IndexOf('.') + 1);

The just compare the two strings "domain1" and "domain2". 只需比较两个字符串“ domain1”和“ domain2”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM