Replace item in querystring
I found this was a more elegant solution
var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());qs.Set("item", newItemValue);Console.WriteLine(qs.ToString());
Lets have this url:https://localhost/video?param1=value1
At first update specific query string param to new value:
var uri = new Uri("https://localhost/video?param1=value1");var qs = HttpUtility.ParseQueryString(uri.Query);qs.Set("param1", "newValue2");
Next create UriBuilder
and update Query
property to produce new uri with changed param value.
var uriBuilder = new UriBuilder(uri);uriBuilder.Query = qs.ToString();var newUri = uriBuilder.Uri;
Now you have in newUri
this value:https://localhost/video?param1=newValue2
I use following method:
public static string replaceQueryString(System.Web.HttpRequest request, string key, string value) { System.Collections.Specialized.NameValueCollection t = HttpUtility.ParseQueryString(request.Url.Query); t.Set(key, value); return t.ToString(); }