Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decode percent-encoded string c# .net

Tags:

c#

.net

How do I decode a string like the following:

name1=ABC&userId=DEF&name2=zyx&payload=%3cSTAT+xmlns%3axsi%3d%22http%3a%2f%2fwww.w3.org%2f2001%2fXMLSchema-instance%22%3e%3cREQ...

Background: I'm accepting an HTTP POST (name value pairs, basically) then converting the byte array to string with:

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

I've tried the HtmlDecode method of WebUtility and HttpUtility but appear to get the same string back.

like image 521
John Spiegel Avatar asked Oct 15 '12 15:10

John Spiegel


2 Answers

This should do the job for you:

System.Uri.UnescapeDataString(str)
like image 51
Andrew Avatar answered Sep 21 '22 22:09

Andrew


Have you tried HttpUtility.UrlDecode?

See here.

Note that this function doesn't do quite the same thing as HttpUtility.HtmlDecode.

Edit: In answer to the question about differences between UrlDecode and UnescapeDataString:

To quote the MSDN page on UnescapeDataString:

Many Web browsers escape spaces inside of URIs into plus ("+") characters; however, the UnescapeDataString method does not convert plus characters into spaces because this behavior is not standard across all URI schemes.

UrlDecode does handle these though, you get different responses 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 better option.

like image 32
Jon Egerton Avatar answered Sep 22 '22 22:09

Jon Egerton