In web development, query strings facilitate communication between clients and servers. A query string is a part of a URL containing data parameters that transmit information from one page to another. In C# development, effectively appending and updating query string values is critical to building dynamic and responsive applications. C# provides several methods and techniques to handle query strings. This article will explore different methods on how to append and update query string values in C#.

Before we dive into this topic, we recommend going through how to create a URL query string.

To download the source code for this article, you can visit our GitHub repository.

With that, let’s start.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Append or Update Query String Using HttpUtility.ParseQueryString Method

The HttpUtility.ParseQueryString() method resides in the System.Web namespace in C# provides a straightforward way to manipulate query strings. This method mainly benefits web applications, offering functionalities to parse, modify, and generate query strings.

Let’s create a method to append and update values to the query string:

public static class QueryStringHelper
{
    private static (NameValueCollection query, string fragment) ModifyQueryStringUsingParseQueryString(
        string url, Dictionary<string, string> queryParams)
    {
        var uriBuilder = new UriBuilder(url);

        var query = HttpUtility.ParseQueryString(uriBuilder.Query);

        foreach (var kvp in queryParams)
        {
            query.Set(HttpUtility.UrlEncode(kvp.Key), kvp.Value);
        }

        return (query, uriBuilder.Fragment);
    }
}

Here, we’ll start by creating a QueryStringHelper class and defining ModifyQueryStringUsingParseQueryString() method that accepts url and queryParams as the input parameter.

Then, we create an instance of the UriBuilder class by passing the url to its constructor. After that, we parse the query string of the URL using HttpUtility.ParseQueryString() method which returns a NameValueCollection representing the key-value pairs of the query string. The ParseQueryString() method handles the URL encoding for the parameter values.

Next, we iterate through the key-value pairs in the queryParams dictionary. For each pair, we call the Set() method of the parsed query string to either set a new parameter or update an existing one. Finally, we return the query and uriBuilder.Fragment as a tuple.

Now, let’s create another method to build the complete URL:

public static string CreateURLUsingParseQueryString(string url, Dictionary<string, string> queryParams)
{
    var result = ModifyQueryStringUsingParseQueryString(url, queryParams);

    return $"{url.Split('?')[0]}?{result.query}{result.fragment}";
}

Here, we create a CreateURLUsingParseQueryString() method inside the same QueryStringHelper class.

Next, we call the ModifyQueryStringUsingParseQueryString() method to obtain the query string.

Finally, we split the original URL at the “?” character using the Split() method, resulting in an array containing the base URL at the zero index. Then, we concatenate the base URL, queryString, and the URL fragment to form the complete URL.

As a last step, let’s invoke the CreateURLUsingParseQueryString() method:

var url = "https://test.com/Books?author=rowling&language=english#section1";

var queryParams = new Dictionary<string, string>
{
    {"genre", "science fiction" },
    {"author", "james martin" }
};

QueryStringHelper.CreateURLUsingParseQueryString(url, queryParams);

Here, we initialize the url which includes an existing query string and a Dictionary<string, string> object containing new key-value pairs that must be appended or updated in the query string. We also include a fragment identifier “#section1.”

We construct the final URL by invoking the CreateURLUsingParseQueryString() method.

Let’s inspect the complete URL:

https://test.com/Books?author=james+martin&language=english&genre=science+fiction#section1

As we can see, the original value “rowling” is replaced with “james+martin” for the “author” parameter, and a new parameter “genre” is added with the value “science+fiction.”

Append or Update Query String Using QueryHelpers.ParseQuery Method

The QueryHelpers.ParseQuery() method, part of the Microsoft.AspNetCore.WebUtilities namespace is a versatile tool for handling query strings in C#.

Let’s start by creating a new method in the QueryStringHelper class:

private static (Dictionary<string, StringValues> query, string fragment) ModifyQueryStringUsingParseQuery(
    string url, Dictionary<string, string> queryParams)
{
    var uriBuilder = new UriBuilder(url);

    var query = QueryHelpers.ParseQuery(uriBuilder.Query);

    foreach (var kvp in queryParams)
    {
        query[kvp.Key] = kvp.Value;
    }

    return (query, uriBuilder.Fragment);
}

Similarly, we create a ModifyQueryStringUsingParseQuery() method and initialize an instance of the UriBuilder class.

Then, we invoke the QueryHelpers.ParseQuery() method by passing the query string of the URL, which returns a Dictionary<string, StringValues> object.

Next, we iterate through the key-value pairs in the queryParams dictionary and update the value of an existing key in the parsed query or add a new key-value pair if the key doesn’t exist.

Finally, we return the tuple containing the modified query parameter and the URL fragment.

Now, let’s invoke the method to build the final URL:

public static string CreateURLUsingParseQuery(string url, Dictionary<string, string> queryParams)
{
    var result = ModifyQueryStringUsingParseQuery(url, queryParams);

    return QueryHelpers.AddQueryString(url.Split('?')[0], result.query) + result.fragment;
}

We call the ModifyQueryStringUsingParseQuery() method to get the queryString. Then, we call the QueryHelpers.AddQueryString() method passing the base URL and the modified queryString, and we concatenate the URL fragment to obtain the complete URL.

So, let’s invoke the method:

QueryStringHelper.CreateURLUsingParseQuery(url, queryParams);

Similarly, we invoke the CreateURLUsingParseQuery() method to fetch the final URL.

Append or Update Query String Using QueryHelpers.AddQueryString Method

The QueryHelpers.AddQueryString() method is present within the Microsoft.AspNetCore.WebUtilities namespace offers a straightforward approach to appending parameters to a query string in C#.

Let’s start defining a method:

private static string AppendQueryStringUsingAddQueryString(string url, Dictionary<string, string?> queryParams)
{
    return QueryHelpers.AddQueryString(url, queryParams);
}

Here, we pass the url and queryParams to the QueryHelpers.AddQueryString() method, which appends the queryParams to the existing query parameters in the URL.

Next, let’s obtain the query string:

public static string CreateURLUsingAddQueryString(string url, Dictionary<string, string?> queryParams)
{
    return AppendQueryStringUsingAddQueryString(url, queryParams);
}

Here, we invoke the AppendQueryStringUsingAddQueryString() method to fetch the queryString.

Finally, let’s build the final URL by calling the CreateURLUsingAddQueryString() method:

QueryStringHelper.CreateURLUsingAddQueryString(url, new Dictionary<string, string?> { { "genre", "science fiction" } });

Now, let’s check the final URL:

https://test.com/Books?author=rowling&language=english&genre=science%20fiction#section1

Here, “genre” with the value “science%20fiction” is appended to the URL.

Append or Update Query String Manually

We manually handle the construction and modification of query strings without relying on predefined utility methods provided by frameworks or libraries. This method directly manipulates the URL components to achieve the desired changes in query parameters.

We fully control the logic and steps in appending or updating query string parameters. While it provides flexibility, it also requires a deep understanding of URL structures, encoding rules, and the intricacies of query string manipulation.

Let’s create a method to manually modify the query string:

private static string ModifyQueryStringManually(string url, Dictionary<string, string> queryParams)
{
    var uri = new Uri(url);
    var existingQuery = uri.Query.TrimStart('?');
    var existingParams = existingQuery
        .Split('&')
        .Select(param => param.Split('='))
        .ToDictionary(pair => pair[0], pair => pair.Length > 1 ? pair[1] : null);

    foreach (var kvp in queryParams)
    {
        existingParams[kvp.Key] = kvp.Value;
    }

    var newQuery = string.Join("&", existingParams.
        Select(kvp => kvp.Value != null 
        ? $"{HttpUtility.UrlEncode(kvp.Key)}={HttpUtility.UrlEncode(kvp.Value)}" : HttpUtility.UrlEncode(kvp.Key)));

    var newUrl = $"{uri.GetLeftPart(UriPartial.Path)}?{newQuery}{uri.Fragment}";

    return newUrl;
}

We begin by creating an Uri instance from the input URL. Then, we use the TrimStart('?') to extract and trim the existing query string.

Next, we iterate through the provided queryParams dictionary, updating or appending values to the corresponding keys in our existing parameters.

To reconstruct the modified query string, we join the key-value pairs, incorporating proper handling for null values, and then concatenate them using the “&” separator. Then, we build the final URL by combining the original URL’s path, the new query string, and any existing fragment.

Now, let’s create the complete URL:

public static string CreateURL(string url, Dictionary<string, string> queryParams)
{
    return ModifyQueryStringManually(url, queryParams);
}

Here, we call the ModifyQueryStringManually() method to build the final URL.

Finally, let’s invoke the CreateURL() method:

QueryStringHelper.CreateURL(url, queryParams)

Let’s inspect the complete URL:

https://test.com/Books?author=james+martin&language=english&genre=science+fiction#section1

As expected, we have the correctly modified URL.

Benchmarking Query String Modifications

Let’s evaluate the four approaches for modifying query strings we’ve covered so far. We will perform a benchmark with the BenchmarkDotNet library to measure the time performance for four approaches.

Let’s assess the benchmark results:

| Method                                 | Mean       | Error    | StdDev   | Median     |
|--------------------------------------- |-----------:|---------:|---------:|-----------:|
| AppendQueryStringUsingAddQueryString   |   299.7 ns |  6.04 ns | 15.04 ns |   293.2 ns |
| ModifyQueryStringUsingParseQuery       | 1,649.3 ns | 19.61 ns | 16.37 ns | 1,646.6 ns |
| ModifyQueryStringManually              | 1,955.8 ns | 32.74 ns | 27.34 ns | 1,951.8 ns |
| ModifyQueryStringUsingParseQueryString | 2,928.5 ns | 43.09 ns | 52.92 ns | 2,920.6 ns |

The AppendQueryStringUsingAddQueryString() method demonstrates superior speed among the tested methods, offering the lowest mean execution time. However, it’s crucial to note that this method is specifically designed for appending new query string parameters and does not support the direct modification of existing values within the query string.

The ModifyQueryStringUsingParseQuery() method and the ModifyQueryStringManually() methods show competitive performance.

The ModifyQueryStringUsingParseQueryString() has a higher mean execution time compared to the other methods.

Choosing the Right Approach

Several factors come into play when determining the most suitable method for appending or updating query strings in C#. The complexity of parameters is a key consideration. Any method may suffice in more straightforward scenarios where only a few parameters require modification. However, for more intricate situations involving multiple parameters, the clarity and efficiency of QueryHelpers.AddQueryString() method stands out as an optimal choice.

Another crucial factor is the compatibility and namespace alignment with our project. If we are working within the ASP.NET Core framework, both QueryHelpers.ParseQuery() and QueryHelpers.AddQueryString() methods are well-aligned with the latest technologies, providing seamless integration and adherence to contemporary practices.

Furthermore, the nature of URL manipulation should guide our method selection. If the task involves comprehensive parsing or manipulation of existing URLs, QueryHelpers.ParseQuery() method shines with its advanced capabilities. On the other hand, for more straightforward tasks like appending parameters without extensive URL manipulation, the streamlined approach of QueryHelpers.AddQueryString() method proves to be efficient and effective.

In addition, manually modifying the query string offers a more hands-on solution for fine-grained control over parameter manipulation. This approach emphasizes manual customization and ensures flexibility for scenarios requiring more control.

Conclusion

In this article, we explored various approaches on how to append and update the values in the existing query string in the URL.

In conclusion, carefully evaluating our project’s requirements should drive decision-making. Understanding the complexity of the parameters, considering the compatibility with the project’s framework, and assessing the specific URL manipulation needs will empower us to make an informed choice among the available methods.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!