How do I decode a URL parameter using C#?
Asked Answered
L

5

179

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

For example, take this URL:

my.aspx?val=%2Fxyz2F
Laundry answered 10/9, 2009 at 12:38 Comment(2)
Hey Tom, couldn't ask on the actual post because it was removed, but did you ever find a solution to Latest Chrome 117.0.5938.89 no more Prints out properly the html page due scaling differences [closed]?Motherless
Please vote for a bug ticket in chrome to solve itLaundry
T
359
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;
}
Tutankhamen answered 2/10, 2010 at 21:26 Comment(4)
@Tutankhamen 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!! :DSexology
IMHO better than the accpeted answer because your first suggestion also works in Portable Class Libaries (PCLs)Locomotive
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*dLevant
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.UrlDecodeDepopulate
P
112
Server.UrlDecode(xxxxxxxx)
Pede answered 10/9, 2009 at 12:41 Comment(2)
which namespace?Affiche
@PolinaC System.Web.HttpServerUtilityBase, but that should already be imported in ASP.NET MVC.Doig
U
81

Have you tried HttpServerUtility.UrlDecode or HttpUtility.UrlDecode?

Uniformed answered 10/9, 2009 at 12:40 Comment(1)
To access the HttpServerUtility.UrlDecode which is an instance method one should use HttpContext.Current.Server.UrlDecode.Classmate
I
32

Try:

var myUrl = "my.aspx?val=%2Fxyz2F";
var decodeUrl = System.Uri.UnescapeDataString(myUrl);
Incitement answered 11/12, 2016 at 16:53 Comment(0)
S
29

Try this:

string decodedUrl = HttpUtility.UrlDecode("my.aspx?val=%2Fxyz2F");
Sarisarid answered 10/9, 2009 at 12:42 Comment(1)
I get: Failed to decrypt using provider 'EncryptionProvider'. Error message from the provider: The RSA key container could not be opened.Precess

© 2022 - 2024 — McMap. All rights reserved.