【问题标题】:Why is Uri.ToString() encoding spaces differently depending on input string?为什么 Uri.ToString() 根据输入字符串对空间进行不同的编码?
【发布时间】:2016-06-30 18:26:30
【问题描述】:

当我在 C# 中的 Uri 上使用 ToString() 时,我遇到了空格编码问题,它的行为似乎因输入字符串而异。
这是我的sn-p代码:

StringBuilder sb1 = new StringBuilder("root");  
sb1.Append("/");
sb1.Append(System.Uri.EscapeDataString("something with spaces"));
Uri result1 = new System.Uri(sb1.ToString(), UriKind.Relative);
// result1.ToString() returns "root/something%20with%20spaces"

StringBuilder sb2 = new StringBuilder("root");  
sb2.Append("/");
sb2.Append(System.Uri.EscapeDataString("something with spacés and accènts")); // "root/something%20with%20spac%C3%A9s%20and%20acc%C3%A8nts"
Uri result2 = new System.Uri(sb2.ToString(), UriKind.Relative);
// result2.ToString() returns "root/something with spacés and accènts"

我不明白。是不是因为它试图在每个输入字符串上找到编码并因为重音而找到不同的编码?

编辑

上面的代码只是我尝试在即时窗口中运行的一个例子,真正的代码 sn-p 在一个 Uri 参数的 getter 中看起来更像这样:

public Uri RelativeUri
{
    get
    {
        List<string> partsOfUri = new List<string>();
        this.getParts(this, parts);
        StringBuilder sb = new StringBuilder(this.Root);
        parts.Reverse();
        parts.ForEach(p =>
        {
            sb.Append("/");
            sb.Append(System.Uri.EscapeDataString(p)); // to avoid problems with '/' in parts
        });
        return new System.Uri(sb.ToString(), UriKind.Relative);
    }
}

这些部分是可以带有斜线、重音符号、空格等的标签。在我的解决方案中的其他地方,我调用MyObject.RelativeUri.ToString(),我得到了这种奇怪的行为。

Encoding.Default 返回System.Text.SBCSCodePageEncoding

【问题讨论】:

    标签: c# uri spaces


    【解决方案1】:

    我尝试运行你的代码。

    它正确地给出了以下结果:

    root/something%20with%20spac%C3%A9s%20and%20acc%C3%A8nts
    

    您能否分享一下您尝试运行此代码的方式和位置?

    仅供参考,Encoding.Default 给我以下结果:

    System.Text.SBCSCodePageEncoding
    

    【讨论】:

    • 我得到与 OP 相同的结果。 sb2.ToString() 会产生预期的输出,但对 result2.ToString() 的以下调用不会 - 这就是空格和特殊字符的编码被撤消的地方。
    • 我在拨打Encoding.Default时也收到System.Text.SBCSCodePageEncoding
    • OP 在sb2 中既有重音又有尖音。只有重音会产生预期的输出。或许只能正确处理一部分字符
    • @hlintrup 即使我打电话给result2.ToString() 我也会得到预期的输出。
    • @hlintrup 我正在使用 OP 提供的确切字符串 something with spacés and accènts
    猜你喜欢
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多