CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

SetUrlEncodedKeys for Query String injection

563 Views
Copy Code Show/Hide Line Numbers
/// <summary>
/// Allows setting of a value in a UrlEncoded string. If the key doesn't exist
/// a new one is set, if it exists it's replaced with the new value.
/// </summary>
/// <param name="urlEncoded">A UrlEncoded string of key value pairs</param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static string SetUrlEncodedKey(string urlEncoded, string key, string value)
{
    if (!urlEncoded.EndsWith("?") && !urlEncoded.EndsWith("&"))
        urlEncoded += "&";
 
    Match match = Regex.Match(urlEncoded, "[?|&]" + key + "=.*?&");
 
    if (match == null || string.IsNullOrEmpty(match.Value))
        urlEncoded = urlEncoded + key + "=" + UrlEncode(value) + "&";
    else
        urlEncoded = urlEncoded.Replace(match.Value, match.Value.Substring(0, 1) + key + "=" + UrlEncode(value) + "&");
 
    return urlEncoded.TrimEnd('&');
}
 
by Rick Strahl
  November 30, 2009 @ 4:07pm
Tags:
Description:
Using this code for a paging component that needs to inject Page No's and other parameters into new URL query strings.

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate