Skip to main content

How to Add a Query String to a URL with QueryHelpers.AddQueryString in ASP.NET Core (C#)

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

A link that carries values, such as https://example.com/search?q=coffee%20%26%20tea, is easy to get wrong by hand: a space or an & in a value has to be encoded, and the first value needs a ? while the rest need &. In ASP.NET Core, QueryHelpers.AddQueryString does all of it for you.

Syntax​

C#
using Microsoft.AspNetCore.WebUtilities;

string url = QueryHelpers.AddQueryString(<url>, <name>, <value>);
string url = QueryHelpers.AddQueryString(<url>, <dictionary>);
PartWhat to put there
<url>The address to add to, with or without a query string already
<name>, <value>One query value and its name
<dictionary>Several names and values at once, as a Dictionary<string, string?>

It returns a new string; the URL you pass in doesn't change. The API reference describes it in one line, Append the given query key and value to the URI, and lists one exception for the first form: ArgumentNullException when value is null.

QueryHelpers is in the Microsoft.AspNetCore.WebUtilities namespace, which every ASP.NET Core project already has, so all you add is the using line.

The Example​

A one-file program, links.cs, builds three links: a search for coffee & tea, a hotel list filtered by city and sorted by price, and the second page of that list. It prints each one.

Prerequisites​

  • The .NET 10 SDK. Check with dotnet --version. This guide used 10.0.404.

Step 1: Write the Code​

Create a file named links.cs:

links.cs in a macOS-style code window: the #:sdk Microsoft.NET.Sdk.Web line, using Microsoft.AspNetCore.WebUtilities, a search link built from q and coffee & tea, a hotels link built from a dictionary with city New York, sort price and coupon null, and a next-page link that adds page 2 to the hotels link.

links.cs
#:sdk Microsoft.NET.Sdk.Web

using Microsoft.AspNetCore.WebUtilities;

// One value: AddQueryString encodes the name and the value for you.
string search = QueryHelpers.AddQueryString("https://example.com/search", "q", "coffee & tea");
Console.WriteLine(search);

// Several values at once, from a dictionary. A value that is null is left out.
Dictionary<string, string?> filters = new()
{
["city"] = "New York",
["sort"] = "price",
["coupon"] = null,
};
string hotels = QueryHelpers.AddQueryString("https://example.com/hotels", filters);
Console.WriteLine(hotels);

// The URL already has a query string, so the new value goes after an &.
string nextPage = QueryHelpers.AddQueryString(hotels, "page", "2");
Console.WriteLine(nextPage);
  • #:sdk Microsoft.NET.Sdk.Web tells .NET to treat this one file as an ASP.NET Core app, which is what makes Microsoft.AspNetCore.WebUtilities available to it. In a project made with dotnet new web, you don't need this line.
  • The first call adds one value, q, to a URL without a query string.
  • The dictionary holds three values, one of them null. The string? in its type allows a value to be null.
  • The last call adds page to the hotels link, which already has a query string.

Step 2: Run It​

Terminal
dotnet run links.cs

dotnet run with a file name runs that single file, without a project. How to Run a Single C# File with dotnet run explains file-based apps.

Output
https://example.com/search?q=coffee%20%26%20tea
https://example.com/hotels?city=New%20York&sort=price
https://example.com/hotels?city=New%20York&sort=price&page=2

A zsh terminal where dotnet run links.cs prints the three links: the search with coffee%20%26%20tea, the hotels link with city=New%20York and sort=price, and the same link with &page=2 added.

The command is the same in zsh, bash and PowerShell. Each line shows one thing AddQueryString did:

  • coffee%20%26%20tea: the spaces became %20 and the & became %26. An & left as it is would have started a new value, so the link would have searched for coffee and added a value named tea.
  • ?city=New%20York&sort=price: the first value got the ?, the next one an &, and coupon, whose value was null, isn't there at all.
  • &page=2: the hotels link already had a ?, so AddQueryString added the new value after an &.

Common Mistakes​

MistakeWhat happensDo this instead
Building the link with $"...?q={text}"A space, & or # in text breaks the linkUse AddQueryString, which encodes each value
Encoding a value yourself, then passing it inIt's encoded twice: a space shows up as %2520Pass the plain value
Passing null as the <value> of the first formArgumentNullException: Value cannot be null. (Parameter 'value')Leave the value out, or use the dictionary form, which skips null values
Expecting the URL you passed in to changeIt doesn't: strings never change in C#Use the returned string

Troubleshooting​

SymptomLikely causeFix
CS0103: The name 'QueryHelpers' does not exist in the current contextThe using Microsoft.AspNetCore.WebUtilities; line is missingAdd it at the top of the file
CS0234: The type or namespace name 'AspNetCore' does not exist in the namespace 'Microsoft'The app isn't an ASP.NET Core app: a console project, or a file-based app without the #:sdk lineAdd #:sdk Microsoft.NET.Sdk.Web to a file-based app, or use a web project
A value is missing from the linkIts value in the dictionary was nullGive it a value, even an empty string

FAQ​

How do I read the values back in ASP.NET Core?​

From the request, with HttpContext.Request.Query["city"], or as a parameter of a minimal API endpoint: ASP.NET Core decodes them for you, so New%20York arrives as New York.

Can one name appear more than once?​

Yes, with the form that takes KeyValuePair<string, StringValues>: a StringValues, from Microsoft.Extensions.Primitives, holds several values for one name, and each becomes its own name=value in the link. A tag with the values wifi and pool came out as ?tag=wifi&tag=pool.

Conclusion​

QueryHelpers.AddQueryString adds one value, or a dictionary of them, to a URL and returns the new link. It encodes spaces and &, chooses ? or & from the URL it gets, and leaves out dictionary values that are null. All it needs is using Microsoft.AspNetCore.WebUtilities; in an ASP.NET Core app.

Additional Resources​