【问题标题】:Extract Web Site name from url从 url 中提取网站名称
【发布时间】:2009-08-13 06:23:15
【问题描述】:

如何从 URL 或链接中提取网站名称。我找到了其他语言的示例,但没有找到 c#。 URL / 链接也不会是我所在的当前页面。

例如http://www.test.com/SomeOther/Test/Test.php?args=1

从中我只需要提取 www.test.com ,请记住它不会总是 .com 并且可以是任何域

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    怎么样:

    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 stringthe 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!");
            }
        }
    }
    

    【讨论】:

    • 出色的正是我所需要的,不敢相信我错过了。
    【解决方案2】:
    this.Request.Url.Host
    

    这个类中的其他属性会很有趣。

    【讨论】:

    • "URL / 链接也不会是我所在的当前页面。"
    【解决方案3】:

    使用正则表达式获取 http:// 和 first / 之后的内容。

    【讨论】:

    • 另外,如果您采用正则表达式方式,请务必排除子域,如果您愿意 :)
    • 我猜他想要子域,其实连www都是test.com的子域
    猜你喜欢
    • 2018-06-26
    • 2012-04-08
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    相关资源
    最近更新 更多