Decoding Encoded URL Parameters in C#
When working with URLs in C#, it's often necessary to decode encoded parameters. For instance, in the URL my.aspx?val=/xyz2F, the parameter value /xyz2F is encoded and needs to be decoded to reveal its true value, which is /xyz2F.
To decode URL parameters in C#, there are two common approaches:
Using Uri.UnescapeDataString():
string url = "my.aspx?val=%2Fxyz2F"; string decodedUrl = Uri.UnescapeDataString(url);
This method decodes the entire URL parameter string, including other encoded portions.
Using HttpUtility.UrlDecode():
string url = "my.aspx?val=%2Fxyz2F"; string decodedUrl = HttpUtility.UrlDecode(url);
This method decodes only the specific URL parameter value, not the entire URL.
In some cases, a URL may be multiply encoded. To fully decode such a URL string, you can use a loop, as shown below:
private static string DecodeUrlString(string url) { string newUrl; while ((newUrl = Uri.UnescapeDataString(url)) != url) url = newUrl; return newUrl; }
The above is the detailed content of How to Decode URL Parameters in C#?. For more information, please follow other related articles on the PHP Chinese website!