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

📚 Interview question

What does an HTTP request and response actually look like on the wire? Walk through the start line, headers and body, explain when data belongs in the route, the query string, a header or the body, and how ASP.NET Core exposes each part to your code.

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.

Beginner Theory Beginner aspnet-core fundamentals headers http http-request web-api

🎯 Key points

  • Request = start line (method, target, version) + headers + blank line + optional body
  • Response = status line (version, status code, reason) + headers + optional body
  • Route identifies the resource; query string filters/shapes it; body carries the representation
  • Headers carry metadata: Content-Type, Accept, Authorization, caching, tracing
  • HTTP/2 multiplexes streams over one connection with HPACK header compression; HTTP/3 runs over QUIC (UDP) with 0/1-RTT setup and no TCP head-of-line blocking; semantics unchanged
  • ASP.NET Core: HttpContext.Request (Method, Path, Query, Headers, Body stream) and HttpContext.Response
  • Model binding maps route/query/header/body onto parameters with [FromRoute], [FromQuery], [FromHeader], [FromBody]
  • Sensitive data goes in Authorization or the body over TLS, never the URL; redact headers in HTTP logging

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 as Host, Accept: application/json and Authorization: Bearer ..., then a blank line, then an optional body. A response has the same shape, except the first line is the status line, like HTTP/1.1 200 OK, followed by headers such as Content-Type and Content-Length, and the body. HTTP/2 and HTTP/3 send the same information as binary frames, with pseudo-headers like :method and :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 on HttpContext.Request: Method, Path, Query, Headers and the Body stream, 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."


The parts of a message

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"}

Where data belongs

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)

How ASP.NET Core exposes it

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands HTTP as a message format, not just as a framework abstraction, and can place API data deliberately.

Green flags

  • Names the start line, headers, blank line and body for both directions
  • Knows HTTP/2 and HTTP/3 change framing, not semantics
  • Places identity in the route, filters in the query, metadata in headers
  • Mentions that URLs are logged and should not carry personal data
  • Can name HttpContext.Request members and the binding attributes

Red flags

  • Thinks headers and the query string are interchangeable
  • Sends bodies with GET as a design choice
  • Cannot explain where Content-Type matters

📚 Learn in depth

1. HTTP is a request-response protocol over a connection

The 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"}            |

2. Framing the body

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.

3. HTTP/2 and HTTP/3: same semantics, different encoding

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

4. The URL

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+).

5. How Kestrel turns bytes into HttpContext

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

6. Body semantics per method

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.

Try it yourself

  1. Run curl -v https://localhost:5001/weatherforecast against a new Web API template and identify the request line, headers and status line in the output.
  2. Repeat with curl --http2 -v and note the lowercase header names and pseudo-headers.
  3. Add a Minimal API endpoint that returns ctx.Request.Method, Path, QueryString and all headers as JSON, and call it with different inputs.
  4. Send a POST with Transfer-Encoding: chunked using curl -H "Transfer-Encoding: chunked" -d @file.json and observe that Content-Length is absent.
  5. Turn on HTTP logging (builder.Services.AddHttpLogging(...)) and see which parts get logged by default and which are redacted.

💻 Code

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}'

⚠ Common mistakes

  • Mistake: Putting tokens, emails or other personal data in the query string. Why it is wrong: URLs are written to server logs, Application Insights, proxy and CDN logs and browser history. Instead: Send credentials in Authorization and personal data in the body.
  • Mistake: Sending a body with GET. Why it is wrong: RFC 9110 gives it no semantics; proxies, CDNs and some clients drop it. Instead: Use query parameters, or a POST to a search resource for complex criteria.
  • Mistake: Forgetting 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).
  • Mistake: Reading 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.
  • Mistake: Treating header names as case-sensitive. Why it is wrong: Header names are case-insensitive, and HTTP/2 lowercases them. Instead: Use IHeaderDictionary (case-insensitive) or typed properties.
  • Mistake: Using the route for optional filters, e.g. /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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the TCP connection or TLS before the request is sent Why: Checks they can describe the full network path beneath the HTTP message
    How to answer
    1. DNS: resolve api.example.com to an IP address (OS cache, then a resolver).
    2. IP routing: packets go from my machine through routers (and usually NAT) to that IP.
    3. TCP: connect to port 443 with a three-way handshake (SYN, SYN-ACK, ACK). One round trip.
    4. TLS: negotiate keys and verify the server's certificate for api.example.com (TLS 1.3: one more round trip).
    5. HTTP: send GET /orders/42 with headers; often a load balancer or reverse proxy terminates TLS and forwards to an app instance.
    6. Response comes back on the same connection, which 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.

  2. When: Candidate mentions [FromBody] or [FromQuery] Why: Checks how ASP.NET Core infers binding sources in controllers vs Minimal APIs
    How to answer

    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.

  3. When: Candidate mentions HTTP/2 or HTTP/3 Why: Checks the practical differences between HTTP versions for a backend engineer
    How to answer

    HTTP is a request/response protocol: method + path + headers (+ body) in, status + headers (+ body) out.

    • Methods: 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.
    • Status codes: 2xx success, 3xx redirect/not modified, 4xx client error (400, 401 vs 403, 404, 409, 422, 429), 5xx server error (500, and 502/503/504 usually from proxies or gateways).
    • Headers: Content-Type, Accept, Authorization, Cache-Control, ETag/If-None-Match, Retry-After, traceparent.
    • Versions: HTTP/1.1 is text with one request at a time per connection; HTTP/2 is binary with multiplexed streams and header compression on one TCP connection; HTTP/3 does the same over QUIC/UDP, removing TCP head-of-line blocking.

↩ Usually asked after

More in HTTP Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me