44

What exactly is the difference between the two functions. The output seems similar except the Uri.EscapeUriString encodes spaces to %20 and Server.UrlEncode encodes them as a + sign.

And the final question which should be used preferably

gotqn
  • 37,902
  • 44
  • 152
  • 231
RC1140
  • 7,882
  • 14
  • 45
  • 69
  • Note that in the title the OP asked about `Uri.EscapeDataString` and in the question he is asking about `Uri.EscapeUriString` they a equivalent. – It-Z May 09 '16 at 09:15
  • I posted a detailed answer to a related question [here](https://stackoverflow.com/a/47877559/62600), and in hindsight it might have been a better fit for this question, although I don't want to double post so hopefully linking to it here will suffice. – Todd Menier Dec 18 '17 at 22:51
  • use WebUtility.UrlEncode according to https://stackoverflow.com/a/47877559/579763 – Ehsan May 15 '18 at 12:55
  • 1
    I found that HttpUtility.UrlEncode does not change exclamantion marks to %21 but ri.EscapeDataString does! – Nick Oct 31 '19 at 11:36

2 Answers2

31

If any one will came across this in the future:

After some digging I have found out that Uri.EscapeDataString is the preferable option. See the the highest voted answer here and this post.

EDIT: Adding the information from the second link here:

We found that in some cases you need to consider using Uri.EscapeDataString. In our case we are encrypting the querystring and found that UrlDecode is converting a plus (+) to space. This was causing us errors during decryption. Using Uri’s Escape and UnescapeDataString makes sense for us when constructing a custom querystring in the URL.

It-Z
  • 1,861
  • 1
  • 19
  • 32
2

I found that HttpUtility.UrlEncode is tolerant to null strings and long strings. It's available both in .NET Core and .NET Framework.

Alex from Jitbit
  • 44,942
  • 15
  • 134
  • 128