Decode the percentage coding of a C # .net string

How to decode a string as shown below:

name1 = ABC & user ID = DEF & name2 = ZYX & payload =% 3cSTAT + XMLNS% 3axsi% 3d% 22http% 3a% 2f% 2fwww.w3.org% 2f2001% 2fXMLSchema instance% 22% 3e% 3cREQ ...

Background: I accept HTTP POST (name value pairs, basically), then converting an array of bytes into a string with:

Encoding.UTF8.GetString(response, 0, response.Length); 

I tried the HtmlDecode method for WebUtility and HttpUtility, but it seems to return the same string.

+7
source share
4 answers

This should do the job for you:

 System.Uri.UnescapeDataString(str) 
+17
source

Have you tried HttpUtility.UrlDecode ?

See here .

Please note that this function does not do the same as HttpUtility.HtmlDecode .

Edit: in response to a question about the differences between UrlDecode and UnescapeDataString :

To quote the MSDN page in UnescapeDataString :

Many web browsers skip spaces within the URI in plus signs ("+"); however, the UnescapeDataString method does not convert plus characters to spaces, because this behavior is not standard for all URI schemes.

UrlDecode handles them, but you get different answers if you try the following:

 string a = Uri.UnescapeDataString(".Net+Framework"); //returns ".Net+Framework" string b = HttpUtility.UrlDecode(".Net+Framework"); //returns ".Net Framework" 

Therefore, it would seem that for better coverage, HttpUtility.UrlDecode is the best option.

+8
source

HttpServerUtility.UrlDecode is what you want.

+3
source
 var result = System.Web.HttpUtility.UrlDecode("name1=ABC&userId=DEF&name2=zyx&payload=%3cSTAT+xmlns%3axsi%3d%22http%3a%2f%2fwww.w3.org%2f2001%2fXMLSchema-instance%22%3e%3cREQ..."); 

gives

 name1=ABC&userId=DEF&name2=zyx&payload=<STAT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><REQ... 

and I expect that this is what you want.

+2
source

All Articles