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

πŸ“š Interview question

What are HEAD and OPTIONS for in an HTTP API? Explain CORS preflight, capability discovery with the Allow header, cheap existence and size checks with HEAD, and what ASP.NET Core does for you automatically versus what you must map yourself.

The HEAD and OPTIONS methods: semantics, CORS preflight, Allow-based capability discovery, HEAD for existence, size and freshness checks, and how ASP.NET Core routing, CORS and static files handle them.

Mid-Level Theory Intermediate aspnet-core cors head http-methods options web-api

🎯 Key points

  • HEAD = GET without a body; same status and headers (Content-Length, ETag, Last-Modified); safe, idempotent, cacheable
  • Uses of HEAD: existence check, size before download, freshness via ETag, health probes
  • OPTIONS describes communication options via the Allow header; a plain OPTIONS differs from a CORS preflight, which also carries Origin + Access-Control-Request-Method
  • Preflight is skipped only for simple requests: GET/HEAD/POST with safelisted headers and form/text content types; JSON bodies, Authorization, custom headers and PUT/PATCH/DELETE trigger it
  • CORS middleware answers preflight with Access-Control-Allow-*; Access-Control-Max-Age caches it per URL (Chromium caps at 2 hours)
  • Minimal APIs don't map HEAD to GET automatically; use MapMethods(["GET","HEAD"]); static files and MVC [HttpHead] cover some cases
  • Kestrel suppresses the body for HEAD responses; still avoid doing expensive work to build one
  • CORS relaxes the browser's same-origin policy, so over-broad policies are a security risk; preflight never requires auth, HEAD does

⏱ 30-second answer

HEAD is GET without the body: same status code and headers (Content-Length, ETag, Last-Modified), so clients can check that a resource exists, how big it is or whether it changed, without downloading it. It is safe, idempotent and cacheable.

OPTIONS asks what the server supports for a URI; the answer is the Allow header. Its main real-world use is the CORS preflight: browsers send OPTIONS with Origin and Access-Control-Request-Method before non-simple cross-origin calls, and ASP.NET Core's CORS middleware answers it.

ASP.NET Core handles preflight and 405 Allow headers for you, but Minimal APIs don't map HEAD automatically. The trade-off: HEAD support is cheap to add but must not cost as much as the GET it replaces.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"HEAD is defined as GET without a response body. The server should return exactly the status and headers a GET would, including Content-Length, ETag and Last-Modified, but no content. That makes it useful for cheap questions: does this document exist, how large is this file before I download it, has it changed since I cached it. It's safe, idempotent and cacheable, like GET. Some load balancers and uptime monitors use HEAD for probes, too.

OPTIONS asks the server which communication options apply to a URI, and the standard answer is an Allow header listing the methods. In practice almost all OPTIONS traffic is CORS preflight: before a cross-origin request that isn't 'simple', like a PUT or a JSON POST with an Authorization header, the browser sends OPTIONS with Origin, Access-Control-Request-Method and Access-Control-Request-Headers. ASP.NET Core's CORS middleware recognises that and answers with the Access-Control-Allow-* headers, and routing produces 405 with an Allow header when the method doesn't match. What it doesn't do is map HEAD for Minimal APIs: MapGet only answers GET, so I use MapMethods with GET and HEAD where clients need it.

For example, at [company] our [document service] served PDFs of [several MB]. A desktop sync client downloaded each file to compare it, about [2 TB] a month of egress. Adding HEAD with an ETag based on the blob's content hash let the client skip unchanged files, and egress dropped [by about 85%]. The mistake I see is implementing HEAD by running the full GET handler, including loading the whole file, and letting the server throw the body away. That saves bandwidth but none of the server cost."


HEAD vs OPTIONS

HEAD OPTIONS
Purpose Metadata of a representation Capabilities of a resource / CORS preflight
Response body Never Optional, rarely used
Key headers Content-Length, ETag, Last-Modified, Content-Type Allow, Access-Control-Allow-*
Safe / idempotent Yes / Yes Yes / Yes
Cacheable Yes No (but preflight results cached per Access-Control-Max-Age)
Auth Same as GET Preflight must not require it

What ASP.NET Core does for you

Behaviour Automatic?
405 with Allow when method doesn't match Yes (endpoint routing)
CORS preflight responses Yes, with AddCors + UseCors / RequireCors
Suppressing the body on HEAD Yes (server ignores body writes for HEAD)
HEAD for static files Yes (UseStaticFiles handles GET and HEAD)
HEAD for Minimal API MapGet No; use MapMethods(["GET", "HEAD"], ...)
HEAD for MVC Only with [HttpHead] or [AcceptVerbs("GET","HEAD")]
Generic OPTIONS listing methods No; usually unnecessary

Production example

A [document sync client] switched from full downloads to HEAD + If-None-Match checks. Of [1.2 million] daily checks, [~95%] returned headers only, and the [Azure Storage egress] bill dropped by [about 85%] with p95 check latency of [40 ms].

πŸ” What the interviewer is checking

Checks understanding of the less common methods, how CORS preflight actually works, and awareness of what the framework does automatically.

Green flags

  • Defines HEAD as GET without body, same headers
  • Uses HEAD for existence, size or freshness checks and makes it cheap
  • Explains the preflight request and response headers
  • Knows Minimal APIs don't map HEAD automatically and routing sets Allow on 405
  • Mentions preflight caching and its per-URL scope

Red flags

  • Thinks OPTIONS is something you implement by hand for CORS
  • Requires auth on preflight
  • Can't name any use for HEAD

πŸ“š Learn in depth

1. HEAD in RFC 9110

The server should send the same header fields it would for GET, though it may omit headers that are only determined while generating the content. Caches can use a HEAD response to update stored GET responses (for example to refresh validators). A HEAD request has no defined body semantics.

2. Using HEAD efficiently in ASP.NET Core

Kestrel and IIS discard body writes for HEAD responses, so a naΓ―ve shared handler works but still does all the work. Check HttpMethods.IsHead(context.Request.Method) and return early after setting headers:

GET  /documents/42 -> load metadata -> open blob stream -> copy 8 MB to response
HEAD /documents/42 -> load metadata -> set Content-Length, ETag -> return (no blob I/O)

If you return Results.File(stream, ...) for HEAD, the stream is opened but not copied; returning metadata only is cheaper still.

3. OPTIONS and the Allow header

OPTIONS /orders/42 HTTP/1.1

HTTP/1.1 204 No Content
Allow: GET, PUT, PATCH, DELETE

A generic OPTIONS handler is rarely worth building for APIs: OpenAPI documents capabilities far better. The Allow header matters most on 405 responses, which ASP.NET Core produces automatically.

4. CORS preflight in detail

A cross-origin request needs a preflight unless it is "simple": method GET, HEAD or POST; only CORS-safelisted request headers (Accept, Accept-Language, Content-Language, Content-Type with application/x-www-form-urlencoded, multipart/form-data or text/plain, and a few others); no ReadableStream body. JSON APIs with tokens always preflight.

1. OPTIONS + Origin + Access-Control-Request-Method + Access-Control-Request-Headers
2. 204 + Access-Control-Allow-Origin / -Methods / -Headers / -Max-Age (+ -Credentials)
3. Browser caches the result per (origin, URL, credentials) for Max-Age
4. Actual request + Origin
5. Response + Access-Control-Allow-Origin (+ Expose-Headers)

Browsers cap Access-Control-Max-Age (Chromium at 7,200 seconds, Firefox at 86,400). Because the cache key includes the URL, an API with /orders/1, /orders/2, ... pays one preflight per distinct URL, which is why some teams route browser traffic through a same-origin BFF.

5. How ASP.NET Core routes preflight

The CORS middleware detects a preflight (OPTIONS + Origin + Access-Control-Request-Method). Endpoint routing's HttpMethodMatcherPolicy matches it to the endpoint for the requested method, so the endpoint's RequireCors policy is used, and the CORS middleware short-circuits with the preflight response. Endpoints must still be routed (UseRouting before UseCors) for endpoint-specific policies to apply.

6. HEAD and OPTIONS through gateways

API Management only forwards operations that are defined; an imported OpenAPI document without HEAD operations means HEAD returns 404 at the gateway. APIM's cors policy can answer preflights itself; if the backend also answers, you can get duplicate Access-Control-Allow-Origin headers, which browsers reject.

Try it yourself

  1. Map MapGet("/files/{id}") and call it with curl -I; then switch to MapMethods(["GET","HEAD"], ...) and compare.
  2. Add an early return for HEAD and measure the difference with dotnet-counters or a simple load test.
  3. Send a preflight from an .http file with and without Access-Control-Request-Method and compare responses.
  4. Set SetPreflightMaxAge(TimeSpan.FromHours(2)) and watch the Network tab skip preflights on repeat calls.
  5. Call an endpoint with the wrong method and read the Allow header on the 405.

πŸ’» Code

HEAD that avoids loading content, and an endpoint-specific CORS policy that handles preflight.

// Program.cs (.NET 10)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IDocumentStore, InMemoryDocumentStore>();
builder.Services.AddCors(o => o.AddPolicy("portal", p => p
    .WithOrigins("https://portal.example.com.au")
    .WithMethods("GET", "HEAD", "PUT")
    .WithHeaders("Authorization", "Content-Type", "If-None-Match")
    .WithExposedHeaders("ETag", "Content-Length")
    .SetPreflightMaxAge(TimeSpan.FromHours(2))));

var app = builder.Build();
app.UseRouting();
app.UseCors();

app.MapMethods("/documents/{id:int}", [HttpMethods.Get, HttpMethods.Head], async (
    int id, HttpContext ctx, IDocumentStore store, CancellationToken ct) =>
{
    var meta = await store.GetMetadataAsync(id, ct);         // cheap: one row
    if (meta is null) return Results.NotFound();

    ctx.Response.Headers.ETag = meta.ETag;
    if (ctx.Request.Headers.IfNoneMatch == meta.ETag) return Results.StatusCode(StatusCodes.Status304NotModified);

    if (HttpMethods.IsHead(ctx.Request.Method))
    {
        ctx.Response.ContentType = meta.ContentType;
        ctx.Response.ContentLength = meta.Length;            // same headers as GET, no blob I/O
        return Results.Empty;
    }

    var stream = await store.OpenContentAsync(id, ct);      // expensive: only for GET
    return Results.File(stream, meta.ContentType);
}).RequireCors("portal");

app.Run();

public sealed record DocumentMetadata(string ContentType, long Length, string ETag);

public interface IDocumentStore
{
    Task<DocumentMetadata?> GetMetadataAsync(int id, CancellationToken ct);
    Task<Stream> OpenContentAsync(int id, CancellationToken ct);
}

public sealed class InMemoryDocumentStore : IDocumentStore
{
    private static readonly byte[] Pdf = new byte[1024];
    public Task<DocumentMetadata?> GetMetadataAsync(int id, CancellationToken ct) =>
        Task.FromResult<DocumentMetadata?>(id == 42 ? new("application/pdf", Pdf.Length, "\"sha-abc\"") : null);
    public Task<Stream> OpenContentAsync(int id, CancellationToken ct) => Task.FromResult<Stream>(new MemoryStream(Pdf));
}
curl -I https://localhost:5001/documents/42                     # HEAD: headers only
curl -i -X OPTIONS https://localhost:5001/documents/42 \
  -H "Origin: https://portal.example.com.au" \
  -H "Access-Control-Request-Method: PUT"                       # preflight

⚠ Common mistakes

  • Mistake: Assuming MapGet also answers HEAD. Why it is wrong: Minimal APIs return 405 for HEAD unless it is mapped. Instead: MapMethods(["GET", "HEAD"], ...) where clients need HEAD.
  • Mistake: Implementing HEAD by running the full GET path. Why it is wrong: The server still loads the content; only bandwidth is saved. Instead: Branch on HttpMethods.IsHead and return headers from metadata.
  • Mistake: Returning different headers for HEAD and GET. Why it is wrong: Caches and clients rely on them matching (e.g. Content-Length, ETag). Instead: Compute headers in one place for both.
  • Mistake: Requiring authentication on OPTIONS preflight. Why it is wrong: Browsers never send credentials on preflight, so it fails with 401. Instead: Let the CORS middleware answer before authentication.
  • Mistake: "Fixing" preflight failures with SetIsOriginAllowed(_ => true) plus AllowCredentials(), or by reflecting any Origin. Why it is wrong: CORS exists to relax the same-origin policy; this lets any website make authenticated calls with the user's cookies and read the responses, exposing personal data. Instead: List exact trusted origins and only the methods and headers clients need.
  • Mistake: Writing a custom OPTIONS handler to fix CORS. Why it is wrong: It duplicates and often contradicts the CORS middleware. Instead: Configure AddCors policies.
  • Mistake: Answering preflight in both API Management and the app. Why it is wrong: Duplicate Access-Control-Allow-Origin headers make browsers reject the response. Instead: One layer owns CORS.
  • Mistake: Not setting Access-Control-Max-Age. Why it is wrong: Every non-simple request costs an extra round trip (browsers default to about 5 seconds of caching). Instead: Set a sensible max age such as 10 minutes to 2 hours.

πŸ› Senior insight: trade-offs

Both methods have a measurable cost, so measure before optimising. In Application Insights, compare the count of OPTIONS requests with the count of real calls: a ratio near 1:1 means every browser call pays an extra round trip. For HEAD, look at egress and response sizes for large representations, and at how many downloads return content the client already had.

To cut preflight cost: raise Access-Control-Max-Age, reduce the number of distinct URLs (the preflight cache is per URL), or remove cross-origin calls entirely with a same-origin BFF or reverse proxy. To get value from HEAD: add it only where a client actually benefits (large files, sync, existence checks) and make it answer from metadata, never by building the full response.

Option When it fits Cost When not to
Higher Access-Control-Max-Age Stable CORS policy Policy changes take effect slowly Rapidly changing origins
Same-origin BFF / reverse proxy First-party SPA, many endpoints An extra component to run Third-party browser clients
HEAD support Large files, sync clients, existence checks Small extra code path Small JSON resources (GET + ETag/304 is enough)

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions safe and idempotent methods Why: Checks method semantics across all HTTP methods
    How to answer

    GET reads, POST creates or runs a command, PUT replaces a resource at a known URI, PATCH partially updates it, DELETE removes it, HEAD is GET without the body, and OPTIONS asks what is allowed (used by CORS preflight).

    • Safe (no intended state change): GET, HEAD, OPTIONS.
    • Idempotent (repeating has the same effect as doing it once): the safe methods plus PUT and DELETE.
    • POST and PATCH are neither, unless you make them so.

    These properties are a contract that caches, proxies, browsers and retry policies rely on: a gateway may retry a timed-out PUT but must not blindly retry a POST. Breaking the contract, such as changing state on GET, causes duplicate side effects and crawler disasters.

  2. When: Candidate mentions CORS middleware or preflight failures Why: Checks diagnosis of middleware order problems including CORS
    How to answer

    All four are symptoms of a pipeline that doesn't match the documented order. I'd write the pipeline out from Program.cs and check it against exception handler β†’ HTTPS β†’ static files β†’ routing β†’ CORS β†’ authentication β†’ authorisation β†’ endpoints. Auth bypass: UseAuthorization missing, before UseRouting, or the endpoint simply has no policy and there is no fallback policy. CORS: UseCors placed after authentication, so the preflight OPTIONS gets a 401 without CORS headers, or the policy isn't applied to the endpoint. Blank 500: UseExceptionHandler registered after the middleware that threw, AddProblemDetails not called, or the response had already started. Static files: files in wwwroot are public by design when UseStaticFiles runs first. I confirm each with Debug-level framework logs and lock the fix in with WebApplicationFactory tests.

πŸ›  Real-world problems: how you handle them

Sync client downloads every document to detect changes
Situation
A [desktop sync client] for a [document management] product kept [~150,000] PDFs in sync for [2,000] firms, re-downloading each file hourly to compare hashes.
Signals
Azure Storage egress of [~2 TB/month] and rising costs; App Service CPU and outbound bandwidth peaks on the hour; slow sync complaints from firms on [regional] connections.
Investigation
Application Insights showed [95%] of GET responses were for files unchanged since the last sync. Request logs showed no conditional headers. Checked that blob metadata already held a content MD5 usable as an ETag.
Resolution
Immediately: added an ETag (from the content hash) and 304 support to GET. Then: mapped HEAD with an early return from metadata, and updated the client to send HEAD with `If-None-Match`, downloading only on change.
Prevention
Performance budget for egress per firm, a dashboard of 304/HEAD ratio, a client SDK that always sends validators, and a load test covering the hourly sync spike.

How to tell it (STAR)

**S:** Our [sync client] re-downloaded every document hourly just to check for changes, costing about [2 TB] of egress a month. **T:** I was asked to cut the cost without changing the sync experience. **A:** I measured that [95%] of downloads were unchanged files, added content-hash ETags and 304 handling, then a cheap HEAD endpoint that answered from metadata only, and worked with the client team to switch to conditional HEAD checks. **R:** Egress fell by [about 85%], hourly CPU peaks flattened, and sync on slow connections went from [minutes to seconds].

↩ Usually asked after

More in HTTP Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me