带有方括号的Uri.EscapeUriString

时间:2013-11-15 14:17:24

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

一些奇怪的问题,但让我们看看它得到了什么样的反应......

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

Uri.EscapeUriString("[")

我明白了:

[

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

%5B

为了使事情进一步复杂化,according to this post Uri.EscapeUriString("[")确实应该返回%5B。帖子写于2012年6月27日。

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

3 个答案:

答案 0 :(得分:5)

这在.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不会转义保留字符这是重要的。

答案 1 :(得分: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      = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"

Uri.EscapeUriString的文档中,它说明了

  

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

因此看起来.NET 4.0中存在一个在4.5.1中修复的错误

答案 2 :(得分:0)

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

改用这个:

Uri.EscapeDataString("[")

这做正确的事情并返回:

%5B

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

相关问题