代码之家  ›  专栏  ›  技术社区  ›  Andrew

当密码或用户名字段包含特殊字符时,System.Uri无法分析

  •  7
  • Andrew  · 技术社区  · 15 年前

    以下代码引发System.UriFormatException:

    var uri = new UriBuilder("ftp://user:pass#word@ftp.somewhere.com:21/fu/bar.zip");
    

    # 密码字段中的符号解决了问题。

    1. 是一个 # 密码字段中的有效字符?
    2. 有什么办法可以逃避吗?
    3. 假设你不能更改密码,你怎么能避开这个问题呢?;-)

    2 回复  |  直到 10 年前
        1
  •  13
  •   Paul Ruane    9 年前

    百分比符号后跟两位十六进制数是字符在URL中转义的方式。23是ASCII表中哈希/磅符号的十六进制值。

    System.Web.HttpUtility.UrlEncode (参考 System.Web

    string username = ...
    string password = ...
    string url = string.Format("ftp://{0}:{1}@ftp.example.com:21/fu/bar.zip",  HttpUtility.UrlEncode(username),
                                                                               HttpUtility.UrlEncode(password));
    
        2
  •  1
  •   Chris    15 年前

    #需要编码,因为它被认为是一个特殊字符。即使这样,我也不确定它会不会奏效。从未尝试过。

    推荐文章