【发布时间】:2009-08-13 06:23:15
【问题描述】:
如何从 URL 或链接中提取网站名称。我找到了其他语言的示例,但没有找到 c#。 URL / 链接也不会是我所在的当前页面。
例如http://www.test.com/SomeOther/Test/Test.php?args=1
从中我只需要提取 www.test.com ,请记住它不会总是 .com 并且可以是任何域
【问题讨论】:
如何从 URL 或链接中提取网站名称。我找到了其他语言的示例,但没有找到 c#。 URL / 链接也不会是我所在的当前页面。
例如http://www.test.com/SomeOther/Test/Test.php?args=1
从中我只需要提取 www.test.com ,请记住它不会总是 .com 并且可以是任何域
【问题讨论】:
怎么样:
new Uri(url).Host
例如:
using System;
class Test
{
static void Main()
{
Uri uri = new Uri("http://www.test.com/SomeOther/Test/Test.php?args=1");
Console.WriteLine(uri.Host); // Prints www.test.com
}
}
查看constructor taking a string 和the Host property 的文档。
请注意,如果它不是“可信”数据源(即它可能是无效的),您可能需要使用 Uri.TryCreate:
using System;
class Test
{
static void Main(string[] args)
{
Uri uri;
if (Uri.TryCreate(args[0], UriKind.Absolute, out uri))
{
Console.WriteLine("Host: {0}", uri.Host);
}
else
{
Console.WriteLine("Bad URI!");
}
}
}
【讨论】:
this.Request.Url.Host
这个类中的其他属性会很有趣。
【讨论】:
使用正则表达式获取 http:// 和 first / 之后的内容。
【讨论】: