[英]C# - Decoding a string does not return the original encoded one
I have a random generated string that I need to put it in a URL, so I encode it like this: 我有一个随机生成的字符串,需要将其放在URL中,因此我将其编码为:
var encodedToken = System.Web.HttpUtility.UrlEncode(token, System.Text.Encoding.UTF8);
In an ASP.NET action method, I receive this token and decode it: 在ASP.NET操作方法中,我收到此令牌并对其进行解码:
var token = System.Web.HttpUtility.UrlDecode(encodedToken, System.Text.Encoding.UTF8);
but these tokens are not the same. 但是这些标记并不相同。 For example the ab+cd
string would encode to ab%2bcd
and decoding the result would give me the ab cd
string (the plus character changed to whitespace). 例如, ab+cd
字符串将编码为ab%2bcd
,解码结果将得到ab cd
字符串(加号字符变为空白)。
So far I have only noticed the +
character problem, there may be others. 到目前为止,我仅注意到+
字符问题,可能还有其他问题。
How can I solve this issue? 我该如何解决这个问题?
In your context, it appears that you don't need to call UrlDecode
(since %2b
decodes to +
and +
decodes to a blank space - ie you have double decoded). 在您的上下文中,您似乎不需要调用UrlDecode
(因为%2b
解码为+
且+
解码为空白-即您已进行了双重解码)。
Given, the framework appears to have already decoded it for you, you may remove your use of UrlDecode
. 鉴于该框架似乎已经为您解码了,您可以删除对UrlDecode
的使用。
According to the Microsoft documentation: 根据Microsoft文档:
You can encode a URL using with the UrlEncode method or the UrlPathEncode method. 您可以使用UrlEncode方法或UrlPathEncode方法对URL进行编码。 However, the methods return different results. 但是,这些方法返回不同的结果。 The UrlEncode method converts each space character to a plus character (+). UrlEncode方法将每个空格字符转换为加号(+)。 The UrlPathEncode method converts each space character into the string "%20", which represents a space in hexadecimal notation. UrlPathEncode方法将每个空格字符转换为字符串“%20”,该字符串以十六进制表示形式表示一个空格。 Use the UrlPathEncode method when you encode the path portion of a URL in order to guarantee a consistent decoded URL, regardless of which platform or browser performs the decoding. 在对URL的路径部分进行编码时,请使用UrlPathEncode方法,以确保解码后的URL一致,无论使用哪种平台或浏览器执行解码。
https://docs.microsoft.com/en-us/dotnet/api/system.web.httputility.urlencode?view=netframework-4.7.2 https://docs.microsoft.com/en-us/dotnet/api/system.web.httputility.urlencode?view=netframework-4.7.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.