Uri 类不处理协议相对 URL

问题描述:

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

* This doesn't happen on Windows but on Mono 4.2.2 Linux (C# Online Compiler).

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

I want to parse the protocol-relative URL and get the host name etc. For now I insert "http:" to the head before processing it since C# Uri class couldn't handle a protocol-relative URL. Could you tell me if there's any better way or any good library?

    // 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"

这有效:

    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) 构造函数.

It also worked for me using the Uri(string) constructor.