I need to pass special characters like #,! etc in URL to Facebook,Twitter and such social sites. For that I am replacing such characters with URL Escape Codes.
return valToEncode.Replace("!", "%21").Replace("#", "%23")
.Replace("$", "%24").Replace("&", "%26")
.Replace("'", "%27").Replace("(", "%28")
.Replace(")", "%29").Replace("*", "%2A");
It works for me, but I want to do it more efficiently.Is there any other way to escape such characters? I tried with Server.URLEncode() but Facebook doesn't render it.
Thanks in advance,
Priya
URL Encoding (Percent Encoding)URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.
A space is assigned number 32, which is 20 in hexadecimal. When you see “%20,” it represents a space in an encoded URL, for example, http://www.example.com/products%20and%20services.html.
Percent-encoding is a mechanism to encode 8-bit characters that have specific meaning in the context of URLs. It is sometimes called URL encoding. The encoding consists of substitution: A '%' followed by the hexadecimal representation of the ASCII value of the replace character.
You should use the **Uri.EscapeDataString** method if you want to have compatibility with RFC3986 standard, where percent-encoding is defined.
For example spaces always will be encoded as %20
character:
var result = Uri.EscapeDataString("a q");
// result == "a%20q"
while for example usage of HttpUtility.UrlEncode
(which is by the way internally used by HttpServerUtility.UrlEncode
) returns +
character:
var result = HttpUtility.UrlEncode("a q")
// result == "a+q"
What's more, the behavior of Uri.EscapeDataString
is compatible with client side encodeURIComponent
javascript method (except the case sensitivity, but RFC3986 says it is irrelevant).
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