Replace item in querystring

I have a URL that also might have a query string part, the query string might be empty or have multiple items.

I want to replace one of the items in the query string or add it if the item doesn't already exists.

I have an URI object with the complete URL.

My first idea was to use regex and some string magic, that should do it.

But it seems a bit shaky, perhaps the framework has some query string builder class?


Solution 1:

I found this was a more elegant solution

var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());
qs.Set("item", newItemValue);
Console.WriteLine(qs.ToString());

Solution 2:

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

Solution 3:

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();
    }

Solution 4:

Maybe you could use the System.UriBuilder class. It has a Query property.

Solution 5:

string link = page.Request.Url.ToString();

if(page.Request.Url.Query == "")
    link  += "?pageIndex=" + pageIndex;
else if (page.Request.QueryString["pageIndex"] != "")
{
    var idx = page.Request.QueryString["pageIndex"];
    link = link.Replace("pageIndex=" + idx, "pageIndex=" + pageIndex);
}
else 
    link += "&pageIndex=" + pageIndex;

This seems to work really well.