Uri 类不处理协议相对 URL [英] Uri class doesn't handle the protocol-relative URL

查看:31
本文介绍了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.

这篇关于Uri 类不处理协议相对 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆