这里的目标是知道给定的URL是否在给定的域中。
例如,我的域名为:www.google.fr 我需要知道这个:http://token.google.fr/news/something是否在域
中我有一个Uri的HashSet,我需要检查所有URL,我的域也在Uri对象中。
有没有办法通过操纵Uri对象来做到这一点?
我尝试比较两个Uri.Authority
,但由于我们可能有前缀和/或后缀,Uri.Compare()
不可用。
答案 0 :(得分:1)
您可以拆分Uri.Authority
并检查TLD和域名,它应该始终是拆分的最后两个元素(假设它是有效的URL)
示例强>
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]);
}
修改强>
如果你的URI有端口,你需要考虑它们。这是一个更好的版本。
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
}
答案 1 :(得分:0)
我可能完全误解了你想要做的事情,但这会有用:
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);
只比较两个字符串“domain1”和“domain2”。