.NET
Query String
NameValueCollection
Parsing
C#

How to parse a query string into a NameValueCollection in .NET

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Parsing query strings is a routine task in .NET web development. Whether you are building an API, processing incoming HTTP requests, or extracting parameters from URLs in a utility application, you need a reliable way to break a query string like ?name=Alice&age=30 into its individual key-value pairs. The .NET framework provides built-in tools that handle URL decoding, duplicate keys, and edge cases, so you do not need to write a manual string-splitting parser. This guide covers the standard approaches in both .NET Framework and .NET Core/.NET 5+.

Using HttpUtility.ParseQueryString (.NET Framework)

The most straightforward method in .NET Framework is HttpUtility.ParseQueryString, which lives in the System.Web namespace. It takes a query string and returns a NameValueCollection:

csharp
1using System.Collections.Specialized;
2using System.Web;
3
4string queryString = "name=Alice&age=30&color=blue";
5NameValueCollection queryParams = HttpUtility.ParseQueryString(queryString);
6
7// Access individual values
8string name = queryParams["name"];   // "Alice"
9string age = queryParams["age"];     // "30"
10
11// Iterate over all keys
12foreach (string key in queryParams.AllKeys)
13{
14    Console.WriteLine($"{key} = {queryParams[key]}");
15}

This method automatically handles URL decoding. For example, a query string containing city=New%20York will correctly decode the value to "New York".

Note that HttpUtility.ParseQueryString expects the query string without the leading ?. If your string starts with ?, strip it first:

csharp
string rawUrl = "?name=Alice&age=30";
string queryString = rawUrl.TrimStart('?');
NameValueCollection queryParams = HttpUtility.ParseQueryString(queryString);

Using QueryHelpers in ASP.NET Core

In ASP.NET Core and .NET 5+, the System.Web namespace is not available. Instead, use QueryHelpers.ParseQuery from Microsoft.AspNetCore.WebUtilities, which returns a Dictionary<string, StringValues>:

csharp
1using Microsoft.AspNetCore.WebUtilities;
2using Microsoft.Extensions.Primitives;
3
4string queryString = "name=Alice&age=30&tag=csharp&tag=dotnet";
5Dictionary<string, StringValues> queryParams =
6    QueryHelpers.ParseQuery(queryString);
7
8// Access a single-value parameter
9string name = queryParams["name"];  // "Alice"
10
11// Access a multi-value parameter
12StringValues tags = queryParams["tag"];  // ["csharp", "dotnet"]
13foreach (string tag in tags)
14{
15    Console.WriteLine(tag);
16}

The StringValues type handles the case where a key appears multiple times in the query string, which is common for filter parameters and checkbox groups.

Handling Duplicate Keys

A query string can contain the same key more than once, such as color=red&color=blue. The NameValueCollection in .NET Framework handles this by storing comma-separated values:

csharp
1string queryString = "color=red&color=blue&color=green";
2NameValueCollection queryParams = HttpUtility.ParseQueryString(queryString);
3
4// Returns "red,blue,green" as a single comma-separated string
5string colors = queryParams["color"];
6
7// To get individual values, use GetValues()
8string[] colorArray = queryParams.GetValues("color");
9// colorArray = ["red", "blue", "green"]

In ASP.NET Core, StringValues natively supports multiple values without comma concatenation, making it more intuitive to work with.

Building Query Strings from a NameValueCollection

You can also go the other direction -- building a query string from a NameValueCollection. The ToString() method produces a properly encoded query string:

csharp
1NameValueCollection queryParams = HttpUtility.ParseQueryString(string.Empty);
2queryParams["name"] = "Alice Smith";
3queryParams["city"] = "New York";
4queryParams["age"] = "30";
5
6string result = queryParams.ToString();
7// result = "name=Alice+Smith&city=New+York&age=30"

This is useful when constructing URLs programmatically, because it handles URL encoding for you automatically.

Accessing Query Strings in ASP.NET Controllers

In an ASP.NET Core controller, you can access query parameters directly from the Request object without manually parsing:

csharp
1[HttpGet("search")]
2public IActionResult Search()
3{
4    string query = Request.Query["q"];
5    string page = Request.Query["page"];
6
7    // Or bind automatically via method parameters
8    return Ok($"Searching for {query}, page {page}");
9}
10
11// With model binding (preferred approach)
12[HttpGet("search")]
13public IActionResult Search([FromQuery] string q, [FromQuery] int page = 1)
14{
15    return Ok($"Searching for {q}, page {page}");
16}

Model binding with [FromQuery] is the preferred approach in ASP.NET Core because it provides automatic type conversion and validation.

Common Pitfalls

  • Forgetting to strip the leading question mark: HttpUtility.ParseQueryString("?name=Alice") treats the ? as part of the first key, resulting in a key named "?name" instead of "name". Always call TrimStart('?') on the input string before parsing.
  • Using System.Web in .NET Core projects: The System.Web namespace is not available in .NET Core or .NET 5+. Attempting to reference HttpUtility without adding the System.Web NuGet compatibility package will cause a compilation error. Use QueryHelpers.ParseQuery from Microsoft.AspNetCore.WebUtilities instead.
  • Assuming single values for duplicate keys: If a query string contains tag=a&tag=b, calling queryParams["tag"] on a NameValueCollection returns "a,b" as a single string. If you split on commas naively, you may break values that legitimately contain commas. Use GetValues() to get a proper string array.
  • Not URL-encoding when building query strings: Manually concatenating query parameters with string interpolation skips URL encoding, which breaks values containing &, =, #, or spaces. Always use HttpUtility.ParseQueryString(string.Empty) or QueryHelpers.AddQueryString to build query strings safely.
  • Case sensitivity assumptions: Query parameter keys are case-sensitive by default in .NET. A request with ?Name=Alice will not match a lookup for queryParams["name"]. If you need case-insensitive lookups, convert keys to lowercase during parsing or use a case-insensitive dictionary.

Summary

  • Use HttpUtility.ParseQueryString in .NET Framework to parse query strings into a NameValueCollection, and QueryHelpers.ParseQuery in .NET Core for a Dictionary<string, StringValues>.
  • Both methods handle URL decoding automatically, so percent-encoded characters like %20 are converted to their proper values.
  • Handle duplicate keys with GetValues() in .NET Framework or iterate over StringValues in .NET Core.
  • Build query strings programmatically using NameValueCollection.ToString() or QueryHelpers.AddQueryString to ensure proper URL encoding.
  • In ASP.NET Core controllers, prefer [FromQuery] model binding over manual query string parsing for cleaner, type-safe code.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.