System.Uri和编码的冒号(:) [英] System.Uri and encoded colon (:)
问题描述
在.Net 4.5之前,似乎System.Uri会取消对已编码的斜杠进行编码,但是此问题已得到修复。参考: https://stackoverflow.com/a/20733619/188740
Before .Net 4.5, it seems that System.Uri would unencode encoded slashes, but this has since been fixed. Reference: https://stackoverflow.com/a/20733619/188740
我在冒号时遇到了同样的问题。 System.Uri仍未对编码的冒号进行编码。示例:
I'm encountering the same problem with colons. System.Uri still unencodes encoded colons. Example:
var uri = new Uri("http://www.example.com/?foo=http%3A%2F%2Fwww.example.com");
var s = uri.ToString(); //http://www.example.com/?foo=http:%2F%2Fwww.example.com
请注意,System.Uri如何将%3A
切换回:
。这是错误吗?最好的解决方法是什么?
Notice how %3A
gets switched back to :
by System.Uri. Is this a bug? What's the best workaround?
推荐答案
如何改用 Uri.AbsoluteUri
?
var s = uri.AbsoluteUri;
// http://www.example.com/?foo=http%3A%2F%2Fwww.example.com
根据源代码, uri.ToString()
看起来具有取消某些部分可见的逻辑,这可以从此处而 .AbsoluteUri
实现。
As per the source, uri.ToString()
looks like it has logic to unescape certain parts which can be seen here whereas .AbsoluteUri
has a much simpler implementation.
Uri.ToString()
一个String实例,其中包含Uri实例的未转义规范表示。除#、?和%外,所有字符均未转义。
A String instance that contains the unescaped canonical representation of the Uri instance. All characters are unescaped except #, ?, and %.
但是,根据示例并在尝试了更多字符串之后,它看起来实际的实现有点像'仅:
, *
和
不转义'
However as per the example and after trying out a few more strings, it looks like the actual implementation is somwhat like 'Only :
, *
and spaces
are unescaped'
%3A (:) // gets unescaped
%20 ( ) // gets unescaped
%2A (*) // gets unescaped
%2b, %26, %23, %24, %25 (+, &, #, $, %) // Remain as-is (escaped)
其他链接
这篇关于System.Uri和编码的冒号(:)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!