0

I have a random generated string that I need to put it in a URL, so I encode it like this:

var encodedToken = System.Web.HttpUtility.UrlEncode(token, System.Text.Encoding.UTF8);

In an ASP.NET action method, I receive this token and decode it:

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).

So far I have only noticed the + character problem, there may be others.

How can I solve this issue?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sasan
  • 3,840
  • 1
  • 21
  • 34
  • 1
    Related: https://stackoverflow.com/q/1005676 – Robert Harvey Jan 07 '19 at 21:28
  • 1
    The treatment of the + sign is described [in the documentation](https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.urlencode?view=netframework-4.7.2). – Robert Harvey Jan 07 '19 at 21:31
  • @Igor I just tried `HttpUtility.UrlDecode("ab%2bcd")` in an Immediate Window and it's returning `ab+cd`. I don't know why in action method I get whitespace. – Sasan Jan 07 '19 at 21:47
  • @mjwills You were right. I was double decoding. I checked the token at the beginning of action method and it had been already decoded. You can post an answer so I can accept it. – Sasan Jan 08 '19 at 08:45

2 Answers2

1

In your context, it appears that you don't need to call UrlDecode (since %2b decodes to + and + decodes to a blank space - i.e. you have double decoded).

Given, the framework appears to have already decoded it for you, you may remove your use of UrlDecode.

mjwills
  • 23,389
  • 6
  • 40
  • 63
  • @panpawel If that is true, it must be a bug. Url decoding + should definitely result in space. Can you point me to a repro? – mjwills Jul 07 '21 at 22:29
-1

According to the Microsoft documentation:

You can encode a URL using with the UrlEncode method or the UrlPathEncode method. However, the methods return different results. The UrlEncode method converts each space character to a plus character (+). The UrlPathEncode method converts each space character into the string "%20", which represents a space in hexadecimal notation. 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.

https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.urlencode?view=netframework-4.7.2

Aaron
  • 1,361
  • 1
  • 13
  • 30