The anatomy of an HTTP/1.1 request and response, where API data belongs (route, query, header, body) and how HttpContext, HttpRequest and HttpResponse expose it in ASP.NET Core.
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.
"An HTTP message is just structured text, at least in HTTP/1.1. A request starts with a request line: the method, the target and the version, like
GET /orders/42?include=lines HTTP/1.1. Then come headers, one per line, such asHost,Accept: application/jsonandAuthorization: Bearer ..., then a blank line, then an optional body. A response has the same shape, except the first line is the status line, likeHTTP/1.1 200 OK, followed by headers such asContent-TypeandContent-Length, and the body. HTTP/2 and HTTP/3 send the same information as binary frames, with pseudo-headers like:methodand:path, but the semantics are identical, so the API contract doesn't change.When I design an endpoint I decide where each piece of data goes. The route identifies which resource:
/customers/17/orders/42. The query string shapes the result: filters, sorting, paging,?status=open&page=2. Headers carry metadata that isn't part of the resource: authentication, content negotiation, caching, correlation ids. The body carries the representation I'm creating or replacing. In ASP.NET Core all of it is onHttpContext.Request:Method,Path,Query,Headersand theBodystream, and model binding maps it to parameters with[FromRoute],[FromQuery],[FromHeader]and[FromBody], or by inference in Minimal APIs.The mistake I see is putting things in the URL that shouldn't be there, like an email address or a token in the query string. URLs end up in IIS and Kestrel logs, Application Insights, proxies and browser history. Under the Privacy Act that's personal information sitting in places nobody controls. So my rule is simple: the URL says what, headers say how and who, the body says the content."
| Part | Request example | Response example |
|---|---|---|
| Start line | POST /orders HTTP/1.1 |
HTTP/1.1 201 Created |
| Headers | Content-Type: application/json, Authorization: Bearer eyJ... |
Location: /orders/42, Content-Type: application/json |
| Blank line | separates headers from body | same |
| Body | {"customerId":17,"lines":[...]} |
{"id":42,"status":"Pending"} |
| Location | Use it for | Avoid |
|---|---|---|
Route (/orders/{id}) |
Resource identity, hierarchy | Optional values, long lists |
| Query string | Filtering, sorting, paging, sparse fields | Secrets, personal data, large payloads |
| Headers | Auth, content negotiation, caching, tracing, idempotency keys | Business data the resource needs |
| Body | Representations to create/update, complex commands | GET bodies (undefined semantics; proxies may drop them) |
| HTTP part | ASP.NET Core API |
|---|---|
| Method | HttpRequest.Method, HttpMethods.IsGet(...) |
| Path and route values | HttpRequest.Path, HttpRequest.RouteValues, [FromRoute] |
| Query string | HttpRequest.Query, [FromQuery], [AsParameters] |
| Headers | HttpRequest.Headers (typed properties like Headers.Accept), [FromHeader] |
| Body | HttpRequest.Body (a Stream), ReadFromJsonAsync<T>(), [FromBody] |
| Response | HttpResponse.StatusCode, Headers, Body, or IResult / TypedResults |
On a [customer portal] the search endpoint took the customer's email as ?email=.... A log review found [thousands of] email addresses in Application Insights request telemetry and the WAF logs. Moving the lookup to a POST body and scrubbing the existing telemetry removed personal data from three log stores and closed a Privacy Act finding.
Checks that the candidate understands HTTP as a message format, not just as a framework abstraction, and can place API data deliberately.
Green flags
HttpContext.Request members and the binding attributesRed flags
Content-Type mattersThe client opens a TCP connection (or QUIC for HTTP/3), optionally negotiates TLS, then sends a request. The server sends exactly one response per request (ignoring 1xx informational responses such as 100 Continue).
Client Server (Kestrel)
| --- TCP + TLS handshake -------------> |
| POST /orders HTTP/1.1 |
| Host: api.example.com.au |
| Content-Type: application/json |
| Content-Length: 48 |
| |
| {"customerId":17,"lines":[...]} |
| --------------------------------------> |
| | middleware -> routing -> endpoint
| <-------------------------------------- |
| HTTP/1.1 201 Created |
| Location: /orders/42 |
| Content-Type: application/json |
| |
| {"id":42,"status":"Pending"} |
The server must know where the body ends. HTTP/1.1 uses either Content-Length (exact byte count) or Transfer-Encoding: chunked (a series of size-prefixed chunks, used when the length isn't known up front, e.g. streaming). HTTP/2 and HTTP/3 use DATA frames with an end-of-stream flag, so Transfer-Encoding is not used there. Ambiguity between the two in HTTP/1.1 is the root of request smuggling attacks, which is why Kestrel rejects requests that send both.
HTTP/2 replaced the text start line with pseudo-headers (:method, :scheme, :authority, :path, :status) and compresses headers with HPACK (QPACK in HTTP/3). Header names must be lowercase. Multiple requests share one connection as streams. For an API designer nothing changes: methods, status codes and headers mean the same thing. RFC 9110 now defines HTTP semantics separately from the wire versions (RFC 9112 for HTTP/1.1, 9113 for HTTP/2, 9114 for HTTP/3).
https://api.example.com.au:443/customers/17/orders?status=open&page=2#top
\___/ \________________/\__/\_________________/ \_______________/ \_/
scheme host port path query fragment
The fragment never reaches the server. The path and query are percent-encoded. The host travels in the Host header (HTTP/1.1) or :authority (HTTP/2+).
Kestrel parses the request line and headers into IHttpRequestFeature, exposes the body as a PipeReader-backed stream, and builds a DefaultHttpContext. Middleware runs in order; routing matches Path and Method to an endpoint; the endpoint's request delegate runs model binding, which pulls values from RouteValues, Query, Headers and the body (via System.Text.Json). Request headers are stored in a dictionary-like IHeaderDictionary with typed accessors (Headers.ContentType, Headers.Authorization).
RFC 9110 says a GET body has no defined semantics; many proxies, CDNs and HttpClient handlers drop or reject it. DELETE bodies are allowed but also poorly supported. Treat POST, PUT and PATCH as the methods that carry bodies.
curl -v https://localhost:5001/weatherforecast against a new Web API template and identify the request line, headers and status line in the output.curl --http2 -v and note the lowercase header names and pseudo-headers.ctx.Request.Method, Path, QueryString and all headers as JSON, and call it with different inputs.Transfer-Encoding: chunked using curl -H "Transfer-Encoding: chunked" -d @file.json and observe that Content-Length is absent.builder.Services.AddHttpLogging(...)) and see which parts get logged by default and which are redacted.A Minimal API that reads each part of a request explicitly, then the same endpoint using model binding.
// Program.cs (.NET 10, nullable enabled)
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// 1. Raw access: useful for diagnostics, rarely for real endpoints.
app.MapPost("/echo/{id:int}", async (HttpContext ctx, CancellationToken ct) =>
{
var request = ctx.Request;
using var reader = new StreamReader(request.Body);
var body = await reader.ReadToEndAsync(ct);
return Results.Ok(new
{
request.Method, // "POST"
Path = request.Path.Value, // "/echo/42"
Id = request.RouteValues["id"], // "42"
Query = request.Query.ToDictionary(q => q.Key, q => q.Value.ToString()),
ContentType = request.ContentType, // "application/json"
Accept = request.Headers.Accept.ToString(),
Body = body
});
});
// 2. Model binding: each value comes from the place that matches its meaning.
app.MapPut("/customers/{customerId:int}/orders/{orderId:int}",
([FromRoute] int customerId,
[FromRoute] int orderId,
[FromQuery] bool notify,
[FromHeader(Name = "X-Correlation-Id")] string? correlationId,
[FromBody] UpdateOrder body) =>
TypedResults.Ok(new { customerId, orderId, notify, correlationId, body.Status }));
app.Run();
public sealed record UpdateOrder(string Status, string? Notes);
curl -v -X PUT "https://localhost:5001/customers/17/orders/42?notify=true" \
-H "Content-Type: application/json" \
-H "X-Correlation-Id: 6f1c" \
-d '{"status":"Shipped","notes":null}'
Authorization and personal data in the body.Content-Type on a request with a JSON body. Why it is wrong: ASP.NET Core picks an input formatter by content type and returns 415 or fails to bind. Instead: Always send Content-Type: application/json (HttpClient's PostAsJsonAsync does it for you).Request.Body twice in middleware. Why it is wrong: It is a forward-only stream; the endpoint later sees an empty body. Instead: Call Request.EnableBuffering() and reset Position, or avoid reading it.IHeaderDictionary (case-insensitive) or typed properties./orders/status/open/page/2. Why it is wrong: It explodes the number of routes and makes caching and documentation harder. Instead: Keep identity in the path, options in the query string.Juniors describe the message format; seniors connect it to operational consequences. Where data sits decides what gets logged, cached, retried and exposed. The URL is the most widely copied part of a request: it lands in access logs, telemetry, CDN keys and Referer headers. Headers are logged less by default, and the body almost never. That is why a senior puts identity in the path, shape in the query, security and protocol metadata in headers, and content in the body.
The HTTP version matters for performance, not for the contract. HTTP/2 multiplexes many requests over one connection and compresses repeated headers (HPACK), so chatty clients and large Authorization tokens cost far less; HTTP/3 over QUIC removes TCP head-of-line blocking and shortens connection setup, which helps mobile clients on lossy networks. Kestrel supports both (HTTP/3 needs TLS and msquic), so the design choice is about what clients and proxies in the path support.
ASP.NET Core gives you tools to keep sensitive data contained: HTTP logging (AddHttpLogging) logs only allow-listed headers and redacts the rest by default, Microsoft.Extensions.Compliance.Redaction redacts classified data in logs, and Application Insights telemetry processors can strip query strings. Authentication should always read credentials from Authorization, never from the query string, except for narrowly scoped cases like WebSocket or SignalR tokens.
| Choice | When it fits | Cost | When not to |
|---|---|---|---|
| Route value | Identity and hierarchy (/orders/42) |
A new route template per shape | Optional or many-valued data |
| Query string | Filters, paging, sorting | Logged everywhere, ~2-8 KB practical limit | Secrets, personal data |
| Header | Auth, negotiation, idempotency, tracing | Less visible, can be stripped by proxies | Business data |
| Body | Create/update payloads, complex search | Not cacheable by default (POST) | GET requests |
api.example.com to an IP address (OS cache, then a resolver).api.example.com (TLS 1.3: one more round trip).GET /orders/42 with headers; often a load balancer or reverse proxy terminates TLS and forwards to an app instance.HttpClient keeps alive and reuses for the next request, skipping steps 1–4.On a cold connection, DNS + TCP + TLS can cost more than the request itself, which is why connection reuse matters.
Model binding takes data from the request (route values, query string, headers, form fields, the JSON body) and from DI, converts it, and passes it to your handler's parameters. You can be explicit with [FromRoute], [FromQuery], [FromHeader], [FromForm], [FromBody] and [FromServices], or let the framework infer. In Minimal APIs: a parameter named in the route template comes from the route, other simple types from the query, registered services from DI, and complex types from the JSON body. In controllers with [ApiController]: complex types from the body, IFormFile from the form, route names from the route, the rest from the query. Only one parameter can read the body. [AsParameters] groups parameters into a record. The trade-off: inference keeps code short, but explicit attributes make the contract obvious in reviews and OpenAPI.
HTTP is a request/response protocol: method + path + headers (+ body) in, status + headers (+ body) out.
GET/HEAD/OPTIONS are safe; GET, PUT, DELETE are idempotent (repeating has the same effect); POST and usually PATCH are not, so retries need an idempotency key.Content-Type, Accept, Authorization, Cache-Control, ETag/If-None-Match, Retry-After, traceparent.Last updated 23 Nov 2026.