ASP.NET
QueryString
Web Development
C#
Programming Tutorials

How to check that Request.QueryString has a specific value or not in ASP.NET?

Master System Design with Codemia

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

Introduction

In ASP.NET, Request.QueryString provides access to URL query parameters as a key-value collection. Checking whether a parameter exists and has a specific value is essential for routing logic, input validation, and conditional page behavior. The exact approach differs slightly between Web Forms, MVC, and ASP.NET Core.

ASP.NET Web Forms / Classic ASP.NET

Request.QueryString returns null when a key is missing, and an empty string when the key exists but has no value.

csharp
1// URL: /page?action=edit&id=42
2
3// Check if key exists
4string action = Request.QueryString["action"];
5if (action != null)
6{
7    // Key exists — action is "edit"
8}
9
10// Check for specific value
11if (Request.QueryString["action"] == "edit")
12{
13    // Execute edit logic
14}
15
16// Safe pattern with null check
17string id = Request.QueryString["id"];
18if (!string.IsNullOrEmpty(id) && int.TryParse(id, out int parsedId))
19{
20    // Use parsedId safely
21}

Distinguish Missing Key from Empty Value

csharp
1// URL: /page?flag=&name=test
2
3string flag = Request.QueryString["flag"];
4string missing = Request.QueryString["nothere"];
5
6// flag is "" (empty string) — key exists but no value
7// missing is null — key does not exist
8
9if (flag != null)
10{
11    Console.WriteLine("flag key is present");
12}

ASP.NET MVC

In MVC controllers, query string values are accessible through Request.QueryString, action parameters, or model binding.

csharp
1// URL: /Products/Search?category=books&page=2
2
3public ActionResult Search(string category, int page = 1)
4{
5    // MVC binds query parameters to action method parameters
6    // category = "books", page = 2
7    // Missing parameters use default values
8
9    if (string.IsNullOrEmpty(category))
10    {
11        return RedirectToAction("Index");
12    }
13
14    ViewBag.Page = page;
15    return View();
16}

For parameters not bound to method arguments:

csharp
1public ActionResult Details()
2{
3    string sort = Request.QueryString["sort"];
4    if (sort == "price")
5    {
6        // Sort by price
7    }
8    else if (sort == "name")
9    {
10        // Sort by name
11    }
12    else
13    {
14        // Default sort
15    }
16
17    return View();
18}

ASP.NET Core

ASP.NET Core provides HttpContext.Request.Query which is an IQueryCollection.

csharp
1// URL: /api/items?status=active&limit=25
2
3public IActionResult GetItems()
4{
5    // Check if key exists
6    if (Request.Query.ContainsKey("status"))
7    {
8        string status = Request.Query["status"];
9        // status = "active"
10    }
11
12    // TryGetValue pattern
13    if (Request.Query.TryGetValue("limit", out var limitValues))
14    {
15        string limit = limitValues.FirstOrDefault();
16        if (int.TryParse(limit, out int parsedLimit))
17        {
18            // Use parsedLimit
19        }
20    }
21
22    return Ok();
23}

Preferred Approach: Model Binding

In ASP.NET Core, binding query parameters to action parameters is the cleanest pattern.

csharp
1[HttpGet("search")]
2public IActionResult Search(
3    [FromQuery] string q,
4    [FromQuery] int page = 1,
5    [FromQuery] int pageSize = 20)
6{
7    if (string.IsNullOrWhiteSpace(q))
8    {
9        return BadRequest("Search query is required");
10    }
11
12    // q, page, and pageSize are automatically parsed from query string
13    return Ok(new { Query = q, Page = page, PageSize = pageSize });
14}

Handling Multiple Values for the Same Key

Query strings can contain duplicate keys (?tag=csharp&tag=dotnet).

csharp
1// ASP.NET Core
2StringValues tags = Request.Query["tag"];
3foreach (string tag in tags)
4{
5    Console.WriteLine(tag);
6}
7
8// Web Forms / MVC
9string allTags = Request.QueryString["tag"];
10// Returns "csharp,dotnet" as comma-separated string
11string[] tagArray = Request.QueryString.GetValues("tag");
12// Returns ["csharp", "dotnet"]

Input Validation

Always validate query string values before using them in database queries or business logic.

csharp
1string rawId = Request.QueryString["id"];
2
3// Never use directly in SQL
4// BAD: $"SELECT * FROM Users WHERE Id = {rawId}"
5
6// Use parameterized queries or model binding
7if (int.TryParse(rawId, out int userId) && userId > 0)
8{
9    // Safe to use userId
10}

Common Pitfalls

  • Not checking for null before comparing values — Request.QueryString["missing"] == "value" returns false safely, but calling methods on null throws NullReferenceException.
  • Confusing empty string (key present, no value) with null (key missing) — use string.IsNullOrEmpty() to handle both.
  • Trusting query string values for security decisions without server-side validation — query parameters can be modified by users.
  • Using Request.QueryString["key"] in ASP.NET Core instead of Request.Query["key"] — the classic QueryString property returns the raw string, not a parsed collection.
  • Not URL-decoding special characters — the framework handles this automatically, but manual string parsing can miss encoded values.

Summary

  • Use Request.QueryString["key"] in Web Forms and MVC, Request.Query["key"] in ASP.NET Core.
  • Check for null to detect missing keys, string.IsNullOrEmpty for missing or empty values.
  • Prefer model binding ([FromQuery] or action parameters) over manual query string access.
  • Always validate and sanitize query string values before using them in business logic or database queries.
  • Use GetValues() or StringValues to handle multi-valued query parameters.

Course illustration
Course illustration

All Rights Reserved.