Uri class doesn't handle the protocol-relative

2019-09-09 06:33发布

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

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"

标签: c# .net url
1条回答
乱世女痞
2楼-- · 2019-09-09 07:01

This works:

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

returns

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

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

查看更多
登录 后发表回答