【问题标题】:Uri.EscapeUriString with square braces带有方括号的 Uri.EscapeUriString
【发布时间】:2013-11-15 14:17:23
【问题描述】:

一个奇怪的问题,但让我们看看它会得到什么样的回应......

如果我编写一个控制台应用程序(VS 2013,.NET 4.5.1)并执行这行代码:

Uri.EscapeUriString("[")

我明白了:

[

但是,如果我在机器上的 LINQPad 中执行相同的操作(嗯,技术上是 Uri.EscapeUriString("[").Dump()),我会得到:

%5B

更复杂的是,according to this postUri.EscapeUriString("[") 确实应该返回 %5B。这篇文章写于 27/06/2012。

我在想,也许 LINQPad 引用的 DLL 比 VS 使用的旧 DLL,但这意味着 EscapeUriString 最近发生了变化,我找不到任何记录。有没有人对可能导致这种行为的原因有任何想法?

【问题讨论】:

  • WT?我可以在 4.5.1 中重现!

标签: c# escaping uri linqpad .net-4.5


【解决方案1】:

这在 .Net 4 和 .Net 4.5 之间发生了变化,您可以通过将框架版本重新定位到 .Net 4 并运行测试程序来验证这一点。

.Net 4 -> 输出“%5B” .net 4.5(或更高版本)-> 输出“[”

这里提到:Application Compatibility in the .NET Framework 4.5

在 Uri.EscapeDataString 、 Uri.EscapeUriString 和 Uri.UnescapeDataString 部分下,其中指出(使用 .Net 4.5):

保留和未保留字符列表现在支持RFC 3986。

具体改动:

Unreserved escaped characters are un-escaped.
EscapeDataString escapes reserved characters based on RFC 3986.
EscapeUriString does not escape reserved characters.
UnescapeDataString does not throw an exception if it encounters an invalid escape sequence.

特别是 EscapeUriString 不会转义保留字符,这一点很重要。

【讨论】:

    【解决方案2】:

    根据RFC 2396,新行为似乎是正确的。在第 566 行它指出:

    566.    Other characters are excluded because gateways and other transport
    567.    agents are known to sometimes modify such characters, or they are
    568.    used as delimiters.
    569. 
    570.    unwise      = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"
    571. 
    572.    Data corresponding to excluded characters must be escaped in order to
    573.    be properly represented within a URI.
    

    在Uri.EscapeUriString 的文档中指出

    默认情况下,EscapeUriString 方法将所有字符(RFC 2396 未保留字符除外)转换为其十六进制表示

    因此,在 .NET 4.0 之前似乎存在一个已在 4.5.1 中修复的错误

    【讨论】:

    • 不正确。在 .NET 4.0 之前,正确遵循 RFC 2396。未转义的字符列在第 469 行,而不是 570 行。dot Net 4.5.1 实际上遵循 RFC 3986 的同一部分中列出的字符,它们是不同的。
    【解决方案3】:

    切勿使用Uri.EscapeUriString() 或HttpUtility.UrlEncode() 对通过URL 传递的数据进行编码

    改用这个:

    Uri.EscapeDataString("[")
    

    这会做正确的事并返回:

    %5B
    

    这适用于 .NET >= 4.NET Core

    【讨论】:

      猜你喜欢
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 2015-03-30
      • 1970-01-01
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      相关资源
      最近更新 更多