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
The URLEncode method applies URL encoding rules, including escape characters, to a specified string. URLEncode converts characters as follows: Spaces ( ) are converted to plus signs (+). Non-alphanumeric characters are escaped to their hexadecimal representation.
EscapeDataString(String) Method is used to convert a string to its escaped representation. Syntax: public static string EscapeDataString (string stringToEscape); Here, it takes the string to escape. Return Value: This method returns a string which contains the escaped representation of stringToEscape.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With