📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you design the query string of an API? Explain how to model filters, arrays and ranges, how encoding works, what the practical length limits are, and when a search should be a POST instead of a GET.

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.

Intermediate Theory Intermediate api-design aspnet-core filtering query-string url-encoding web-api

🎯 Key points

  • Query string shapes a collection: filter, sort, page, sparse fields; identity stays in the path
  • Pick one array convention: repeated keys (?status=open&status=held) bind natively; comma lists need a custom binder
  • Ranges: explicit names like createdFrom/createdTo, ISO 8601 dates with offsets
  • Percent-encode values (Uri.EscapeDataString / QueryHelpers.AddQueryString); + vs %20 ambiguity
  • Practical URL limit ~2,000-8,000 chars: Kestrel request line 8 KB, IIS maxQueryString 2,048, proxies/CDNs vary
  • Allow-list filter and sort fields mapped to expressions; never pass raw strings into SQL or dynamic LINQ (injection)
  • No personal data or tokens in URLs (logs, telemetry, Referer, history): Privacy Act exposure; use POST body
  • Use POST /resources/search for large or sensitive criteria; lose GET caching; bind GETs with [AsParameters] and cap pageSize

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 a string[] without any custom code; comma-separated lists are nicer to read but need a custom binder or TryParse type. For ranges I use explicit names like createdFrom and createdTo with 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.AddQueryString or Uri.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's maxQueryString defaults 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/search with 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."


Conventions

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

Length limits (defaults)

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 vs POST for search

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can design consistent, safe query parameters and knows the encoding, limit and privacy pitfalls.

Green flags

  • Keeps identity in the path and shaping in the query
  • Chooses a single array and range convention and knows how ASP.NET Core binds it
  • Knows percent-encoding and the + pitfall
  • Names concrete length limits and the symptoms (414, 404.15)
  • Allow-lists sort and filter fields and caps page size

Red flags

  • Builds query strings by concatenation
  • Passes raw sort/filter strings to SQL or dynamic LINQ
  • Puts personal data in URLs

📚 Learn in depth

1. Anatomy and encoding

/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.

2. How ASP.NET Core binds the query

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.

3. Why limits exist

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)

4. Security and privacy

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.

5. POST for search and the QUERY method

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.

Try it yourself

  1. Bind string[] status from ?status=a&status=b in a Minimal API, then try ?status=a,b and see the difference.
  2. Send ?offset=+08:00 and ?offset=%2B08:00 and log what arrives.
  3. Set KestrelServerOptions.Limits.MaxRequestLineSize = 1024 and send a long query to see the 414.
  4. Build a URL with QueryHelpers.AddQueryString from a dictionary containing &, + and spaces and inspect the output.
  5. Check an Application Insights resource with requests | where url contains "@" for leaked emails.

💻 Code

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
});

⚠ Common mistakes

  • Mistake: Building URLs by string interpolation. Why it is wrong: &, # and + in values break the query or change its meaning. Instead: QueryHelpers.AddQueryString or Uri.EscapeDataString.
  • Mistake: Putting personal data or tokens in the query string. Why it is wrong: It lands in logs, telemetry, browser history and Referer headers. Instead: POST body or headers.
  • Mistake: Passing the 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.
  • Mistake: Mixing array conventions (status=a,b here, status[]=a there). Why it is wrong: Clients need special cases per endpoint. Instead: One documented convention, ideally repeated keys.
  • Mistake: Sending hundreds of ids in a GET. Why it is wrong: Hits URL limits at some layer and fails with 414 or 404.15 before reaching your telemetry. Instead: POST /resources/search or batch endpoints.
  • Mistake: No upper bound on pageSize. Why it is wrong: A client asking for 100,000 rows can exhaust memory and SQL resources. Instead: Validate and cap it.
  • Mistake: Date filters without offsets. Why it is wrong: Ambiguous across Australian time zones and daylight saving. Instead: ISO 8601 with offset, or UTC.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions comma-separated lists or custom binding Why: Checks TryParse, BindAsync and custom model binders
    How to answer

    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.

  2. When: Candidate mentions what belongs in the path vs query vs body Why: Checks the basics of HTTP message structure
    How to answer

    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.

↩ Usually asked after

More in HTTP Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me