【问题标题】:Uri class doesn't handle the protocol-relative URLUri 类不处理协议相关的 URL
【发布时间】:2016-11-03 06:34:36
【问题描述】:

*编辑:这不会在 Windows 上发生,而是在 Mono 4.2.2 Linux (C# Online Compiler) 上发生。

我想解析协议相对 URL 并获取主机名等。现在我在处理它之前将“http:”插入头部,因为 C# Uri 类无法处理协议相对 URL。你能告诉我是否有更好的方法或任何好的图书馆?

    // Protocol-relative URL
    var uriString = "//www.example.com/bluh/bluh.css";
    var uri = new Uri(uriString);
    Console.WriteLine(uriString); // "//www.example.com/bluh/bluh.css"
    Console.WriteLine(uri.Host); // "Empty" string

    // Absolute URL
    var fixUriString = uriString.StartsWith("//") ? "http:" + uriString : uriString;
    var fixUri = new Uri(fixUriString);
    Console.WriteLine(fixUriString); // "http://www.example.com/bluh/bluh.css"
    Console.WriteLine(fixUri.Host); // "www.example.com"

【问题讨论】:

标签: c# .net url


【解决方案1】:

这行得通:

    Uri uri = null;
    if(Uri.TryCreate("//forum.xda-developers.com/pixel-c", UriKind.Absolute, out uri))
    {
        Console.WriteLine(uri.Authority);
        Console.WriteLine(uri.Host);
    }

返回

forum.xda-developers.com
forum.xda-developers.com

使用 Uri(string) 构造函数也对我有用。

【讨论】:

  • 谢谢!你让我意识到单声道在 Linux 上的工作方式不同。我切换到 Windows,然后 Uri(string) 完美运行。
猜你喜欢
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
  • 2014-07-01
  • 2016-11-26
相关资源
最近更新 更多