Percent Encoding special characters before sending to URL


I need to pass special characters like # ,! etc. in the URL of Facebook, Twitter, and such social sites. To do this, I replace these characters with the URL code Escape.
 return valToEncode.Replace("!", "%21").Replace("#", "%23") .Replace("$", "%24").Replace("&", "%26") .Replace("'", "%27").Replace("(", "%28") .Replace(")", "%29").Replace("*", "%2A");

This works for me, but I want to do it more efficiently. Is there any other way to avoid such characters? I tried with Server.URLEncode () , but Facebook does not display it.

Thanks in advance,
Priya

+5
source share
4 answers

You should use the Uri.EscapeDataString method if you want to be compatible with RFC3986 , where percent encoding is defined.

, %20:

var result = Uri.EscapeDataString("a q");
// result == "a%20q"

HttpUtility.UrlEncode (, , HttpServerUtility.UrlEncode), +:

var result = HttpUtility.UrlEncode("a q") 
// result == "a+q"

Uri.EscapeDataString javascript encodeURIComponent ( , RFC3986 , ).

+20

System.Web.HttpUtility.UrlEncode System.Net.WebUtility.UrlEncode .

+1

, , .

Regex.Replace(Uri.EscapeDataString(s), "[\!*\'\(\)]", Function(m) Uri.HexEscape(Convert.ToChar(m.Value(0).ToString())))

, .

Uri.EscapeDataString .Net 4.5.

RFC 3986.

. .NET Framework 4.5.

RFC 3986. , RFC 2396, , , RFC 2396 RFC 3986, Uri.EscapeDataString.

+1

"PercentEncode" rfc 3986. HttpUtility.EncodeUrl ('!', '*', '(', ')') , % .

public static string PercentEncode(string value)  
{  
    StringBuilder retval = new StringBuilder();  
    foreach (char c in value)  
    {   
        if ((c >= 48 && c <= 57) || //0-9  
            (c >= 65 && c <= 90) || //a-z  
            (c >= 97 && c <= 122) || //A-Z                    
            (c == 45 || c == 46 || c == 95 || c == 126)) // period, hyphen, underscore, tilde  
        {  
            retval.Append(c);  
        }  
        else  
        {  
            retval.AppendFormat("%{0:X2}", ((byte)c));  
        }  
    }  
    return retval.ToString();  
}  
+1

All Articles