175

How can I decode an encoded URL parameter using C#?

For example, take this URL:

my.aspx?val=%2Fxyz2F
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom
  • 6,725
  • 24
  • 95
  • 159

5 Answers5

349
string decodedUrl = Uri.UnescapeDataString(url)

or

string decodedUrl = HttpUtility.UrlDecode(url)

Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop:

private static string DecodeUrlString(string url) {
    string newUrl;
    while ((newUrl = Uri.UnescapeDataString(url)) != url)
        url = newUrl;
    return newUrl;
}
ogi
  • 3,530
  • 2
  • 15
  • 2
  • @ogi Thanks for that! I didn't know it didn't fully work with just one call! I ran `Uri.UnescapeDataString` twice and got what I wanted!! :D – c0nfus3d Dec 31 '13 at 02:28
  • 3
    IMHO better than the accpeted answer because your first suggestion also works in Portable Class Libaries (PCLs) – Daniel Veihelmann Feb 05 '16 at 11:09
  • 3
    best answer! but consider how your params are nested before you fully decode. e.g. a param value could be an encoded URL which itself has a param with another encoded URL, If you fully decode it in one go, you won't be able to tell what was what anymore. it would be like yanking all the parens out of an algebra statement. a=((b+c)*d) if you fully unescape it, the meaning of components can be lost a=b+c*d – DanO Oct 04 '16 at 19:07
  • 4
    UnescapeDataString is not sufficient as it will not handle several cases (for instance parameters in a URL that contain a space use '+' but UnescapeDataString intentionally doesn't convert those to spaces). Uri handles more than just URL, as the question is asking about URL we should use HttpUtility.UrlDecode – Lorenz03Tx Aug 04 '17 at 21:37
112
Server.UrlDecode(xxxxxxxx)
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
81

Have you tried HttpServerUtility.UrlDecode or HttpUtility.UrlDecode?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    To access the `HttpServerUtility.UrlDecode` which is an instance method one should use `HttpContext.Current.Server.UrlDecode`. – BornToCode Aug 30 '16 at 09:16
32

Try:

var myUrl = "my.aspx?val=%2Fxyz2F";
var decodeUrl = System.Uri.UnescapeDataString(myUrl);
Matheus Miranda
  • 1,755
  • 2
  • 21
  • 36
29

Try this:

string decodedUrl = HttpUtility.UrlDecode("my.aspx?val=%2Fxyz2F");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Canavar
  • 47,715
  • 17
  • 91
  • 122
  • I get: Failed to decrypt using provider 'EncryptionProvider'. Error message from the provider: The RSA key container could not be opened. – Allan F Mar 01 '23 at 02:24