C#
query string
URL building
programming
.NET

How to build a query string for a URL in C?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Building a query string in C# sounds simple until the values contain spaces, ampersands, or existing query parameters. The safe solution is to encode keys and values correctly and avoid hand-written string concatenation whenever the input is dynamic.

In practice, a good query-string builder needs to do three things well: preserve the base URL, URL-encode each component, and keep the code readable.

What a Query String Actually Is

A query string is the section after ? in a URL, made of key=value pairs separated by &. For example:

text
https://example.com/search?q=csharp&page=2

That looks trivial, but string concatenation breaks quickly with values like "C# tips & tricks" unless you encode them first.

A Simple Framework-Neutral Approach

If you want an approach that works in ordinary C# code without web-framework helpers, build the query from encoded pairs and append it through UriBuilder:

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5var baseUri = new Uri("https://example.com/search");
6var parameters = new Dictionary<string, string?>
7{
8    ["q"] = "C# tips & tricks",
9    ["page"] = "2",
10    ["sort"] = "recent"
11};
12
13string query = string.Join(
14    "&",
15    parameters
16        .Where(kvp => kvp.Value is not null)
17        .Select(kvp =>
18            $"{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value!)}"));
19
20var builder = new UriBuilder(baseUri)
21{
22    Query = query
23};
24
25Console.WriteLine(builder.Uri);

This prints a valid URL with encoded values. The important part is Uri.EscapeDataString, which protects reserved characters from breaking the URL structure.

Why Raw String Concatenation Is Fragile

This code looks tempting:

csharp
string url = "https://example.com/search?q=" + searchTerm + "&page=" + page;

It works until searchTerm contains spaces, &, ?, =, or non-ASCII characters. Then the server may parse the wrong parameters or reject the request.

The rule is simple: concatenate structure, but encode user or dynamic data.

Preserving Existing Query Parameters

Sometimes the base URL already contains a query string. In that case, you should merge rather than blindly replace.

A small helper keeps this manageable:

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5static string AddQueryParameters(string baseUrl, IDictionary<string, string> extra)
6{
7    var uri = new Uri(baseUrl);
8    var existing = uri.Query.TrimStart('?')
9        .Split('&', StringSplitOptions.RemoveEmptyEntries)
10        .Select(part => part.Split('=', 2))
11        .ToDictionary(
12            pair => Uri.UnescapeDataString(pair[0]),
13            pair => pair.Length > 1 ? Uri.UnescapeDataString(pair[1]) : "");
14
15    foreach (var item in extra)
16    {
17        existing[item.Key] = item.Value;
18    }
19
20    string query = string.Join(
21        "&",
22        existing.Select(kvp =>
23            $"{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value)}"));
24
25    return new UriBuilder(uri) { Query = query }.Uri.ToString();
26}
27
28Console.WriteLine(AddQueryParameters(
29    "https://example.com/search?lang=en",
30    new Dictionary<string, string> { ["page"] = "2", ["q"] = "dotnet" }));

That pattern is useful when you are extending URLs returned by another part of the application.

When You Are in ASP.NET Core

If you are already in an ASP.NET Core project, you may prefer a built-in helper instead of writing the join logic yourself. The core idea stays the same: pass structured data and let a library handle encoding.

Even then, it is still worth understanding the manual version so you know what the helper is protecting you from.

Security and Design Considerations

Query strings are visible in browser history, logs, monitoring tools, and proxy layers. That means they are fine for filtering, paging, search, and sorting, but a poor place for secrets or credentials.

Also remember that query strings are strings. If the server expects arrays, dates, booleans, or nested objects, decide on a clear encoding convention rather than guessing one ad hoc in several places.

Common Pitfalls

The most common mistake is forgetting to URL-encode values. A single & inside user input can split one parameter into two.

Another mistake is encoding the whole URL instead of only the keys and values. That can corrupt the ?, &, and = separators that are supposed to remain structural.

Developers also overwrite existing query parameters accidentally by assigning a new query string without reading the current one first.

Finally, do not put sensitive data in the query string just because it is convenient. Query parameters travel farther through logs and caches than many developers expect.

Summary

  • Build query strings from encoded key-value pairs, not from raw concatenated strings.
  • 'Uri.EscapeDataString is a good low-level tool for encoding query components.'
  • 'UriBuilder helps attach the query string to a base URL cleanly.'
  • Merge existing query parameters carefully instead of replacing them accidentally.
  • Use query strings for public request parameters, not secrets.

Course illustration
Course illustration

All Rights Reserved.