Query string design for APIs: filter, array and range conventions, percent-encoding, URL length limits in Kestrel, IIS, proxies and browsers, binding in ASP.NET Core, and when to switch search to POST.
The query string shapes a collection: filters, sorting, paging and field selection, while the path holds identity. Pick conventions and apply them everywhere: repeated keys for arrays (?status=open&status=held, which ASP.NET Core binds to string[] natively), explicit range names (createdFrom, createdTo) with ISO 8601 values, and allow-listed sort and filter fields so nothing raw reaches SQL.
Values must be percent-encoded, and URLs have practical limits: Kestrel caps the request line at 8 KB, IIS defaults maxQueryString to 2,048 characters, and proxies vary. URLs are logged everywhere, so never put personal data or secrets in them. When criteria get large, complex or sensitive, use POST /orders/search with a body. The trade-off: GET is cacheable and bookmarkable; POST handles big or private criteria but loses caching.
"I use the query string for anything that narrows or shapes a collection, never for identity.
/orders?status=open&customerId=17&sort=-createdAt&page=2&pageSize=50. The important thing is consistency across the API, so I define conventions once. For multiple values I use repeated keys,status=open&status=held, because ASP.NET Core binds that to astring[]without any custom code; comma-separated lists are nicer to read but need a custom binder orTryParsetype. For ranges I use explicit names likecreatedFromandcreatedTowith ISO 8601 dates including the offset, because 'today' in Perth isn't 'today' in Sydney. Sort fields come from an allow-list, so a client can't sort on an unindexed column or inject anything.Encoding matters: values must be percent-encoded, so I build URLs with
QueryHelpers.AddQueryStringorUri.EscapeDataString, not string concatenation. A plus sign is the classic bug, because form encoding treats+as a space. And there are limits: Kestrel's request line limit is 8 KB by default, IIS'smaxQueryStringdefaults to 2,048 characters, and some proxies and CDNs cut off earlier. If a client sends 500 ids, that GET will fail somewhere.So when criteria are large, deeply structured or sensitive, I expose
POST /orders/searchwith a JSON body. That costs HTTP caching and bookmarkability, and POST isn't idempotent by definition even though search has no side effects, so I document that it's safe to retry. The mistake I see is putting personal data in query strings: a search by email or Medicare number ends up in every log along the way. That goes in a POST body."
| Need | Convention | Example |
|---|---|---|
| Equality filter | Field name | ?status=open |
| Multiple values | Repeated key | ?status=open&status=held |
| Range | From/To suffix |
?createdFrom=2026-11-01T00:00:00%2B08:00 |
| Text search | q or search |
?q=kettle |
| Sort | Allow-listed field, - for descending |
?sort=-createdAt,total |
| Paging | page/pageSize or cursor/limit |
?cursor=eyJpZCI6...&limit=50 |
| Sparse fields | fields |
?fields=id,status,total |
| Layer | Limit |
|---|---|
| Kestrel | MaxRequestLineSize 8 KB; total headers 32 KB |
| IIS / HTTP.sys | maxQueryString 2,048 chars, maxUrl 4,096 |
| Azure Application Gateway / Front Door | URL limits in the 8-32 KB range (check current docs) |
| Browsers | Tens of KB, but older guidance is ~2,000 chars for safety |
| GET with query | POST /search | |
|---|---|---|
| Cacheable | Yes | No (in practice) |
| Bookmark/share | Yes | No |
| Size | Limited | Large |
| Logged | Everywhere | Body rarely logged |
| Semantics | Safe, idempotent | Must document as safe to retry |
A [logistics] dashboard sent GET /shipments?ids=... with up to [800] ids. Requests over [2,048] characters failed with 404.15 from IIS on [one] legacy host and with 414 at the gateway. Moving bulk lookups to POST /shipments/search removed the [~1.5%] failure rate, and the normal filter GETs stayed cacheable.
Checks that the candidate can design consistent, safe query parameters and knows the encoding, limit and privacy pitfalls.
Green flags
+ pitfallRed flags
/orders?status=open&status=held&q=tea%20%26%20coffee&sort=-createdAt
\_________/ \_________/ \__________________/ \_____________/
key=value pairs separated by &; values percent-encoded
RFC 3986 reserves characters such as &, =, +, #, / and ?. & inside a value must become %26. The application/x-www-form-urlencoded convention encodes space as +; RFC 3986 encodes it as %20. ASP.NET Core's query parser decodes + as a space, so a literal plus (a phone number like +61..., or a time zone offset +08:00) must be sent as %2B. Uri.EscapeDataString and QueryHelpers.AddQueryString do this correctly; string interpolation does not.
HttpRequest.Query is an IQueryCollection of StringValues, so repeated keys are preserved. Binding to string[], int[] or List<T> from repeated keys works in both MVC and Minimal APIs. Comma-separated values need a type with static bool TryParse(string, IFormatProvider?, out T) (Minimal APIs) or a custom model binder (MVC). [AsParameters] binds a record or class of query parameters in Minimal APIs. Nested objects (filter[status]=open) are an MVC model-binding convention, not a standard, and Minimal APIs don't support them out of the box.
The request line and headers are read into buffers before any app code runs. Limits protect against memory abuse. When a limit is hit, you'll see 414 URI Too Long (Kestrel, gateways), 404.14/404.15 (IIS request filtering) or 400 from a proxy, often without reaching your app's telemetry.
Client -> CDN/WAF -> Gateway -> Kestrel
limit A limit B limit C effective limit = min(A, B, C)
Query strings appear in server access logs, Application Insights requests.url, WAF logs, browser history and Referer headers sent to third parties. Personal information (email, phone, Medicare or tax file numbers) in a URL is a Privacy Act exposure, and potentially a notifiable data breach if logs leak. Filters must be allow-listed: map sort=createdAt to an expression through a dictionary, never through OrderBy(string) with raw input or string-built SQL.
POST /orders/search is the common workaround for large or sensitive criteria. The IETF HTTP working group's draft QUERY method (safe and idempotent, with a body) addresses this gap; as of late 2026 it is still not broadly supported by clients, proxies or ASP.NET Core's routing helpers, so don't depend on it for public APIs. You could map it with MapMethods("/orders", ["QUERY"], ...) for internal experimentation.
string[] status from ?status=a&status=b in a Minimal API, then try ?status=a,b and see the difference.?offset=+08:00 and ?offset=%2B08:00 and log what arrives.KestrelServerOptions.Limits.MaxRequestLineSize = 1024 and send a long query to see the 414.QueryHelpers.AddQueryString from a dictionary containing &, + and spaces and inspect the output.requests | where url contains "@" for leaked emails.Binding a filter record with [AsParameters], allow-listing sort fields, and an alternative POST search.
// Program.cs (.NET 10)
using System.Linq.Expressions;
using Microsoft.AspNetCore.WebUtilities;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
Order[] data = [new(1, "open", 120m, DateTimeOffset.UtcNow.AddDays(-2)), new(2, "held", 80m, DateTimeOffset.UtcNow)];
// GET /orders?status=open&status=held&createdFrom=2026-11-01T00:00:00%2B08:00&sort=-createdAt&pageSize=50
app.MapGet("/orders", ([AsParameters] OrderQuery q) =>
{
if (q.PageSize is < 1 or > 100) return Results.ValidationProblem(new Dictionary<string, string[]>
{ ["pageSize"] = ["pageSize must be between 1 and 100."] });
var query = data.AsQueryable();
if (q.Status is { Length: > 0 }) query = query.Where(o => q.Status.Contains(o.Status));
if (q.CreatedFrom is not null) query = query.Where(o => o.CreatedAt >= q.CreatedFrom);
if (q.CreatedTo is not null) query = query.Where(o => o.CreatedAt < q.CreatedTo);
if (!SortFields.TryApply(ref query, q.Sort))
return Results.ValidationProblem(new Dictionary<string, string[]>
{ ["sort"] = [$"Allowed sort fields: {string.Join(", ", SortFields.Allowed)}."] });
return Results.Ok(query.Take(q.PageSize).ToList());
});
// Large or sensitive criteria go in a body.
app.MapPost("/orders/search", (OrderSearch body) =>
Results.Ok(data.Where(o => body.Ids.Contains(o.Id)).ToList()));
app.Run();
public sealed record Order(int Id, string Status, decimal Total, DateTimeOffset CreatedAt);
public sealed record OrderQuery(
string[]? Status,
DateTimeOffset? CreatedFrom,
DateTimeOffset? CreatedTo,
string? Sort,
int PageSize = 50);
public sealed record OrderSearch(int[] Ids);
public static class SortFields
{
private static readonly Dictionary<string, Expression<Func<Order, object>>> Map =
new(StringComparer.OrdinalIgnoreCase)
{
["createdAt"] = o => o.CreatedAt,
["total"] = o => o.Total
};
public static IEnumerable<string> Allowed => Map.Keys;
public static bool TryApply(ref IQueryable<Order> query, string? sort)
{
if (string.IsNullOrWhiteSpace(sort)) { query = query.OrderBy(o => o.Id); return true; }
var desc = sort.StartsWith('-');
if (!Map.TryGetValue(sort.TrimStart('-'), out var key)) return false; // allow-list only
query = desc ? query.OrderByDescending(key) : query.OrderBy(key);
return true;
}
}
// Client side: build query strings with encoding, never by concatenation.
var url = QueryHelpers.AddQueryString("/orders", new Dictionary<string, string?>
{
["createdFrom"] = "2026-11-01T00:00:00+08:00", // '+' encoded as %2B
["q"] = "tea & coffee" // '&' encoded as %26
});
&, # and + in values break the query or change its meaning. Instead: QueryHelpers.AddQueryString or Uri.EscapeDataString.sort parameter straight into dynamic LINQ or SQL. Why it is wrong: Injection risk and sorts on unindexed columns that time out. Instead: Allow-list sort fields mapped to expressions.status=a,b here, status[]=a there). Why it is wrong: Clients need special cases per endpoint. Instead: One documented convention, ideally repeated keys.POST /resources/search or batch endpoints.pageSize. Why it is wrong: A client asking for 100,000 rows can exhaust memory and SQL resources. Instead: Validate and cap it.Query strings feel trivial, but they are a public contract that is hard to change: once clients rely on status=a,b, you are stuck with it. A senior writes the conventions into the API guidelines (array format, range naming, sort syntax, paging) and builds one shared binder or filter type so every endpoint behaves the same. That consistency matters more than which convention wins.
The GET vs POST decision is a trade-off between HTTP's built-in benefits and practical constraints. Keep simple filters on GET for caching and shareable links; move to POST only when size, structure or privacy forces it, and say in the docs that the POST is safe to retry.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| GET + flat query | Simple filters, paging | URL limits, visible in logs | Personal data, big id lists |
GET + OData $filter |
Internal/reporting APIs needing rich queries | Hard to secure and index for | Public APIs with strict performance budgets |
| POST /search | Large, nested or sensitive criteria | No HTTP caching, not bookmarkable | Simple, cacheable lookups |
It depends on where the value comes from. For a value in the route, query or a header, give the type a static TryParse (ideally implement IParsable<T>): both Minimal APIs and MVC (since .NET 7) then bind it like an int, which is perfect for strongly typed IDs like OrderId or a comma-separated list wrapper. When a Minimal API parameter needs several parts of the request (headers plus query, or the user), use static BindAsync(HttpContext, ParameterInfo). For controllers with complex rules, write a custom IModelBinder with an IModelBinderProvider, which records errors in ModelState. If the type is inside the JSON body, none of these apply: you need a JsonConverter. The trade-off: TryParse is simplest and portable across both models; binders give full control but only work in MVC.
An HTTP message has three parts: a start line, headers and an optional body. A request's start line is the method, target and version (GET /orders/42?include=lines HTTP/1.1); a response's is the status line (HTTP/1.1 200 OK). Headers carry metadata such as Content-Type, Accept and Authorization; a blank line separates them from the body.
In an API, the route identifies the resource, the query string filters or shapes it, headers carry cross-cutting metadata, and the body carries the representation being created or changed. ASP.NET Core exposes all of this through HttpContext.Request and HttpContext.Response, and model binding maps it onto parameters. The trade-off: URLs are logged and cached everywhere, so anything sensitive goes in headers or the body, never the query string.
Last updated 23 Nov 2026.