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
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
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.
I found that HttpUtility.UrlEncode is tolerant to null strings and long strings. It's available both in .NET Core and .NET Framework.
But I also found that Uri.EscapeDataString is 4X faster and uses less memory
| Method | Mean | Error | StdDev | Gen0 | Allocated |
|---|---|---|---|---|---|
| EscapeDataString | 19.52 ns | 0.333 ns | 0.018 ns | - | - |
| HttpUtilityUrlEncode | 88.69 ns | 41.303 ns | 2.264 ns | 0.0191 | 120 B |