TExcelTAD
Home › ASP.NET Core › Route & Query Parameters

Route & Query Parameters

A request carries data in several places: the path (/products/42), the query string (?page=2&sort=price), headers and the body. Minimal APIs bind each handler parameter to one of these sources — by convention, or explicitly with an attribute.

Binding by convention

For simple types (int, string, Guid, DateOnly, enums, …) the rule is:

  1. If the route template has a parameter with the same name, use the route value.
  2. Otherwise, use the query string value with that name.
csharp
app.MapGet("/products/{id:int}", (int id, string? currency) =>
    
quot;Product {id}, prices in {currency ?? "EUR"}");
bash · try it yourself
$ curl -s localhost:5000/products/42
$ curl -s "localhost:5000/products/42?currency=USD"
Product 42, prices in EUR
Product 42, prices in USD

id comes from the route; currency isn't in the template, so it comes from the query string. Names are matched case-insensitively.

Required vs optional

Nullability decides whether a parameter is required:

Parameter Missing from the request
int page 400 Bad Request — required
int? page page is null
int page = 1 page is 1 (default value)
string q 400 — required (with nullable reference types enabled)
string? q q is null
csharp
app.MapGet("/search", (string q, int page = 1, int pageSize = 10) =>
    new { Query = q, Page = page, PageSize = pageSize });
bash · try it yourself
$ curl -s "localhost:5000/search?q=laptop&page=3"
$ curl -s -o /dev/null -w "%{http_code}\n" "localhost:5000/search?page=3"
$ curl -s -o /dev/null -w "%{http_code}\n" "localhost:5000/search?q=laptop&page=three"
{"query":"laptop","page":3,"pageSize":10}
400
400

A value that can't be converted (page=three) also produces a 400. In Development the response body explains the problem; in Production it is empty unless you enable ProblemDetails (see the Error Handling lesson).

How conversion works

For simple types, ASP.NET Core converts the text with the type's static TryParse method. That means you can bind your own types too — just give them a public static bool TryParse(string? value, out T result):

csharp · try it yourself
using System;
using System.Globalization;

// Simulate binding "?from=2026-03-10&color=12,200,80" the way ASP.NET Core does: via TryParse
string? fromText = "2026-03-10";
string? colorText = "12,200,80";

if (DateOnly.TryParse(fromText, CultureInfo.InvariantCulture, out var from))
    Console.WriteLine(
quot;from = {from:yyyy-MM-dd} ({from.DayOfWeek})"); if (Rgb.TryParse(colorText, out var color)) Console.WriteLine(
quot;color = {color}"); Console.WriteLine(
quot;bad color parses? {Rgb.TryParse("red", out _)}"); record Rgb(byte R, byte G, byte B) { // The exact signature minimal APIs look for public static bool TryParse(string? value, out Rgb result) { result = new Rgb(0, 0, 0); var parts = value?.Split(','); if (parts is not { Length: 3 }) return false; if (byte.TryParse(parts[0], out var r) && byte.TryParse(parts[1], out var g) && byte.TryParse(parts[2], out var b)) { result = new Rgb(r, g, b); return true; } return false; } public override string ToString() =>
quot;#{R:X2}{G:X2}{B:X2}"; }
from = 2026-03-10 (Tuesday)
color = #0CC850
bad color parses? False

With that Rgb type, app.MapGet("/paint", (Rgb color) => color.ToString()) would bind ?color=12,200,80 automatically.

Explicit sources: the [From…] attributes

When convention isn't enough, say exactly where a value comes from:

Attribute Source Example
[FromRoute] Route value [FromRoute] int id
[FromQuery] Query string [FromQuery(Name = "p")] int page
[FromHeader] Request header [FromHeader(Name = "X-Tenant")] string tenant
[FromBody] JSON body [FromBody] Todo todo
[FromForm] Form fields / files [FromForm] IFormFile file
[FromServices] Dependency injection [FromServices] IClock clock
csharp
using Microsoft.AspNetCore.Mvc;   // the [From…] attributes live here

app.MapGet("/reports/{year:int}", (
    [FromRoute] int year,
    [FromQuery(Name = "fmt")] string format,
    [FromHeader(Name = "X-Tenant")] string tenant) =>
        
quot;{tenant}: {year} report as {format}");
bash · try it yourself
$ curl -s "localhost:5000/reports/2026?fmt=pdf" -H "X-Tenant: acme"
acme: 2026 report as pdf

Arrays and repeated keys

A query key can appear several times. Bind it to an array:

csharp
app.MapGet("/filter", (int[] ids) => 
quot;Selected: {string.Join(", ", ids)}");
bash · try it yourself
$ curl -s "localhost:5000/filter?ids=3&ids=8&ids=21"
Selected: 3, 8, 21

Grouping parameters with [AsParameters]

Handlers with many parameters get hard to read. Collect them in a class or record and mark it [AsParameters]; each property is bound as if it were a separate parameter:

csharp
app.MapGet("/products", ([AsParameters] ProductQuery query) =>
    
quot;page {query.Page}, size {query.PageSize}, sort {query.Sort ?? "name"}"); record ProductQuery(int Page = 1, int PageSize = 20, string? Sort = null);

Special types you can always ask for

Some types are bound without any attribute because the framework provides them:

Type What you get
HttpContext Everything about the current request/response
HttpRequest / HttpResponse Just one side of it
CancellationToken Signalled when the client disconnects
ClaimsPrincipal The current user

Reading the query string by hand is still possible: context.Request.Query["sort"]. Here is what that raw data looks like before binding — a plain dictionary of string values:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

string queryString = "?q=desk&tags=wood&tags=oak&page=2";

var query = queryString.TrimStart('?')
    .Split('&')
    .Select(pair => pair.Split('='))
    .GroupBy(kv => kv[0], kv => Uri.UnescapeDataString(kv[1]))
    .ToDictionary(g => g.Key, g => g.ToArray());

foreach (var (key, values) in query)
    Console.WriteLine(
quot;{key} = [{string.Join(", ", values)}]"); int page = int.TryParse(query["page"][0], out var p) ? p : 1; Console.WriteLine(
quot;next page: {page + 1}");
q = [desk]
tags = [wood, oak]
page = [2]
next page: 3

Test yourself

For app.MapGet("/items/{id}", (int id, string? sort) => …), where does sort come from?

  1. The route
  2. The query string
  3. A header
  4. The JSON body

A handler has the parameter int page and the request omits page. What happens?

  1. page is 0
  2. page is null
  3. The request fails with 400 Bad Request
  4. The route doesn't match (404)

Which attribute reads a value from an HTTP header?

  1. [FromQuery]
  2. [FromHeader]
  3. [FromServices]
  4. [FromBody]