Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Percentage Encoding of special characters before sending it in the URL


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

like image 509
Priya Avatar asked Apr 24 '13 07:04

Priya


People also ask

How do I encode a percentage in a URL?

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.

What is the meaning of %20 in URL?

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.

What do percentages mean in a URL?

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.


1 Answers

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

like image 155
jwaliszko Avatar answered Oct 16 '22 11:10

jwaliszko