Created
October 1, 2012 15:28
-
-
Save AmitKB/3812506 to your computer and use it in GitHub Desktop.
Add / Update url paramter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string AddToUrlQuerystring(HttpRequest req, string paramName, object paramValue, bool encodeValue) | |
{ | |
var sb = new StringBuilder(); | |
string ParamValue; | |
// Encode parameter value or not | |
if (encodeValue) | |
ParamValue = SPEncode.UrlEncode(paramValue.ToString()); | |
else | |
ParamValue = paramValue.ToString(); | |
// Add url without query string | |
sb.AppendFormat("{0}{1}{2}{3}", req.Url.Scheme,Uri.SchemeDelimiter, | |
req.Url.Authority, req.Url.AbsolutePath); | |
// Add '?' to url | |
sb.Append("?"); | |
bool IsParamExist = false; | |
foreach(string key in req.QueryString.AllKeys) | |
{ | |
// make sure key exist or it is not empty | |
if (string.IsNullOrEmpty(key)) { continue; } | |
string KeyUrlEncoded = SPEncode.UrlEncode(key); | |
string KeyValueUrlEncoded = SPEncode.UrlEncode(req.QueryString[key]); | |
sb.Append("&"); | |
sb.Append(SPEncode.UrlEncode(key)); | |
sb.Append("="); | |
if (key == paramName) | |
{ | |
// Key already exist, so replace value only | |
sb.Append(ParamValue); | |
IsParamExist = true; | |
} | |
else | |
sb.Append(KeyValueUrlEncoded); | |
} | |
if (!IsParamExist) | |
{ | |
sb.Append("&" + SPEncode.UrlEncode(paramName) + "=" + ParamValue); | |
} | |
// remove the first occurance of "?&" | |
string pattern = Regex.Escape("?&"); | |
var rx = new Regex(pattern); | |
return rx.Replace(sb.ToString(), "?", 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment