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

📚 Interview question

Show me how you call an ASP.NET Core Minimal API from the browser with fetch. Load and create items as JSON, handle HTTP errors properly (fetch doesn't throw on 404 or 500), read a ProblemDetails validation response, and cancel the request with AbortController when the user navigates away or types again.

Writing a typed fetch wrapper in TypeScript against an ASP.NET Core Minimal API: JSON requests, checking response.ok, parsing ProblemDetails and ValidationProblemDetails, timeouts and cancellation with AbortController and AbortSignal, and how the server sees the cancellation.

Junior Coding Intermediate abortcontroller fetch-api frontend minimal-apis problem-details typescript

🎯 Key points

  • fetch only rejects on network failure or abort, not on 4xx/5xx: check response.ok
  • Set Content-Type: application/json and JSON.stringify the body
  • Parse application/problem+json (RFC 9457): type, title, status, detail, traceId, and errors dictionary for validation
  • Map ValidationProblemDetails errors to form fields
  • Handle 204 No Content, and check Content-Type before parsing: proxies return HTML or empty error bodies
  • AbortController.abort() cancels; AbortSignal.timeout(ms) for timeouts; ignore AbortError
  • Server sees cancellation via HttpContext.RequestAborted / CancellationToken parameter, which cancels EF Core and HttpClient calls
  • credentials: 'include' needed for cookies cross-origin

⏱ 30-second answer

Wrap fetch once. Send JSON with method, a Content-Type: application/json header and JSON.stringify(body). Remember fetch only rejects on network errors or abort: a 400 or 500 resolves normally, so always check response.ok. On failure, if the content type is application/problem+json, parse the ProblemDetails (title, status, detail, and for validation an errors dictionary keyed by field) and throw a typed error the UI can map to form fields. For cancellation create an AbortController, pass its signal, and call abort() when the component unmounts or a newer search starts; combine with AbortSignal.timeout() for a deadline and ignore AbortError. On the server, ASP.NET Core binds a CancellationToken to RequestAborted, so the database query stops too. The trade-off: a small wrapper is enough; reach for a library only when you need caching and retries.

🗣 Full answer (senior)

How I would answer this in an interview

"fetch returns a promise of a Response, and the first thing I tell people is that it only rejects when the request couldn't complete at all: DNS failure, connection refused, CORS blocked or aborted. A 404 or 500 is a successful fetch with ok set to false. So I never sprinkle raw fetch calls around; I write one small wrapper that sets the JSON headers, checks response.ok, handles 204, and turns error responses into a typed error.

ASP.NET Core makes the error side easy because it speaks ProblemDetails, RFC 9457. With AddProblemDetails(), unhandled exceptions and status codes come back as application/problem+json with type, title, status, detail and a traceId, and validation failures, whether from [ApiController], TypedResults.ValidationProblem or the built-in Minimal API validation in .NET 10, include an errors object like { \"Email\": [\"Email is required.\"] }. My wrapper parses that into an ApiError with fieldErrors, so the form can put each message under the right input, and everything else shows a generic message with the trace id for support.

For cancellation I use AbortController. In a search box, each keystroke aborts the previous request so slow responses can't overwrite newer results; in React, the effect clean-up aborts when the component unmounts. AbortSignal.timeout(10_000) gives a deadline, and AbortSignal.any combines both. The browser closes the request, Kestrel notices, and the CancellationToken parameter in my endpoint, which is HttpContext.RequestAborted, fires, so EF Core cancels the SQL command. The mistake I see is wrapping fetch in try/catch and assuming the catch handles 500s. It doesn't, and that's how error pages end up rendering undefined."


What fetch does with each outcome

Outcome Promise response.ok What to do
2xx Resolves true Parse JSON (unless 204)
4xx / 5xx Resolves false Parse ProblemDetails, throw ApiError
Network down, DNS, CORS blocked Rejects TypeError n/a Show offline/retry message
abort() or timeout Rejects AbortError / TimeoutError n/a Usually ignore silently

ProblemDetails fields

Field Meaning UI use
status HTTP status Branch on 400/401/403/404/409
title Short summary Toast or banner
detail Specific explanation (safe text only) Banner
errors Field → messages (validation) Inline field errors
traceId (extension) Correlates with server logs "Quote this reference"

Production example

A product search fired a request per keystroke; on 4G, responses arrived out of order and users saw results for "ca" after typing "cable". Aborting the previous request and debouncing 250 ms cut API calls by 70% and removed the stale-results bug; server-side, RequestAborted stopped about 40% of SQL queries early during peak.

🔍 What the interviewer is checking

Checks that the candidate can write correct, robust browser code against their own API, not just happy-path fetches.

Green flags

  • States that fetch doesn't reject on 4xx/5xx and checks ok
  • Parses ProblemDetails and maps errors to fields
  • Uses AbortController and handles AbortError
  • Connects client abort to the server's CancellationToken

Red flags

  • Calls res.json() blindly
  • No error or cancellation handling
  • Returns exception text to the client

📚 Learn in depth

1. The request path

React component
   |  apiFetch('/api/products?q=cab', { signal })
   v
fetch()  -> browser network stack -> (CORS checks if cross-origin)
   |                                   |
   |                                Kestrel -> routing -> endpoint(ct = RequestAborted)
   |                                   |
   |<--------- Response (status, headers, body stream)
   v
res.ok ? res.json() : parse problem+json -> throw ApiError

Response arrives as soon as headers do; res.json() then reads the body stream. Aborting during either phase rejects the pending promise.

2. Why fetch doesn't throw on HTTP errors

The Fetch standard models HTTP faithfully: a 500 is still a valid HTTP response. Libraries like axios choose to throw on non-2xx; fetch leaves it to you. Hence the wrapper.

3. ProblemDetails in ASP.NET Core

  • builder.Services.AddProblemDetails() registers IProblemDetailsService.
  • app.UseExceptionHandler() + app.UseStatusCodePages() produce ProblemDetails for exceptions and empty error responses.
  • TypedResults.ValidationProblem(dictionary) returns HttpValidationProblemDetails with errors.
  • In .NET 10, builder.Services.AddValidation() validates DataAnnotations on Minimal API parameters and returns a 400 ValidationProblem automatically.

Field names in errors follow the property names as serialised (camelCase JSON naming in recent versions), so match them to form field names consistently.

4. Cancellation end to end

AbortController.abort()
   -> browser cancels the HTTP/1.1 connection or sends RST_STREAM (HTTP/2)
   -> Kestrel marks the request aborted
   -> HttpContext.RequestAborted is cancelled
   -> CancellationToken passed to EF Core / HttpClient throws OperationCanceledException
   -> ASP.NET Core logs it at a low level, no 500 sent (client is gone)

AbortSignal.timeout(ms) creates a signal that aborts with a TimeoutError; AbortSignal.any([a, b]) aborts when either does. Both are supported in all current evergreen browsers.

5. Cookies and credentials

Same-origin requests send cookies by default (credentials: 'same-origin'). Cross-origin requests need credentials: 'include' and a CORS policy with AllowCredentials() and an explicit origin.

Try it yourself

  1. Build the Minimal API below, call it from the browser and confirm a 400 still resolves the fetch promise.
  2. Throw an exception in an endpoint and inspect the application/problem+json body in DevTools → Network → Response.
  3. Add await Task.Delay(5000, ct) to an endpoint, abort from the client after 1 s and log ct.IsCancellationRequested on the server.
  4. Type quickly into a search box with and without abort-previous logic and watch the Network panel's cancelled requests.
  5. Write a Vitest test for apiFetch with a mocked fetch returning a ValidationProblem.

💻 Code

The endpoint and the TypeScript that calls it.

// Program.cs (.NET 10)
using System.ComponentModel.DataAnnotations;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();   // RFC 9457 responses for errors
builder.Services.AddValidation();       // .NET 10: DataAnnotations on Minimal API parameters
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();

var todos = new List<Todo>();

app.MapGet("/api/todos", async (string? q, CancellationToken ct) =>
{
    await Task.Delay(300, ct); // stands in for an EF Core query using ct
    return TypedResults.Ok(todos.Where(t => q is null || t.Title.Contains(q, StringComparison.OrdinalIgnoreCase)));
});

app.MapPost("/api/todos", (CreateTodo input) =>
{
    var todo = new Todo(todos.Count + 1, input.Title);
    todos.Add(todo);
    return TypedResults.Created($"/api/todos/{todo.Id}", todo);
});

app.Run();

public sealed record Todo(int Id, string Title);
public sealed record CreateTodo([property: Required, StringLength(100, MinimumLength = 3)] string Title);
// api.ts
export type ProblemDetails = {
  type?: string; title?: string; status?: number; detail?: string;
  errors?: Record<string, string[]>; traceId?: string;
};

export class ApiError extends Error {
  constructor(public status: number, public problem: ProblemDetails | null) {
    super(problem?.title ?? `HTTP ${status}`);
  }
  get fieldErrors(): Record<string, string[]> { return this.problem?.errors ?? {}; }
}

export async function apiFetch<T>(url: string, init: RequestInit & { json?: unknown } = {}): Promise<T> {
  const { json, headers, ...rest } = init;
  const res = await fetch(url, {
    ...rest,
    headers: { Accept: 'application/json', ...(json !== undefined && { 'Content-Type': 'application/json' }), ...headers },
    body: json !== undefined ? JSON.stringify(json) : rest.body,
  });

  if (!res.ok) { // fetch does NOT throw for 4xx/5xx
    const isProblem = res.headers.get('content-type')?.includes('application/problem+json');
    throw new ApiError(res.status, isProblem ? ((await res.json()) as ProblemDetails) : null);
  }
  if (res.status === 204) return undefined as T;
  return (await res.json()) as T;
}

// search.ts: abort the previous request on every new search, with a 10 s deadline
let current: AbortController | undefined;
export async function search(q: string) {
  current?.abort();
  current = new AbortController();
  const signal = AbortSignal.any([current.signal, AbortSignal.timeout(10_000)]);
  try {
    return await apiFetch<{ id: number; title: string }[]>(`/api/todos?q=${encodeURIComponent(q)}`, { signal });
  } catch (e) {
    if (e instanceof DOMException && e.name === 'AbortError') return null; // superseded: ignore
    throw e;
  }
}

⚠ Common mistakes

  • Mistake: Assuming catch handles HTTP 500s. Why it is wrong: fetch resolves on any HTTP response. Instead: Check response.ok and throw.
  • Mistake: Calling res.json() on every error. Why it is wrong: Proxies return HTML 502 pages or empty bodies, so parsing throws and hides the real error. Instead: Check Content-Type first.
  • Mistake: Forgetting Content-Type: application/json on POST. Why it is wrong: ASP.NET Core returns 415 Unsupported Media Type. Instead: Set it in the wrapper.
  • Mistake: Building query strings by concatenation. Why it is wrong: Special characters break the URL. Instead: encodeURIComponent or URLSearchParams.
  • Mistake: Showing AbortError as a failure to the user. Why it is wrong: It's an intentional cancel. Instead: Ignore aborts explicitly.
  • Mistake: Not accepting a CancellationToken in the endpoint. Why it is wrong: Server keeps querying for a client that left. Instead: Bind CancellationToken and pass it down.
  • Mistake: Returning ex.Message in detail. Why it is wrong: Leaks internals. Instead: Generic detail plus a traceId to correlate with logs.

🏛 Senior insight: trade-offs

The wrapper is the contract enforcement point between frontend and backend: one place for headers, auth, error mapping, telemetry and cancellation. Standardising on ProblemDetails server-side means the frontend writes error handling once. For screens that need caching, deduplication and background refresh, TanStack Query on top of this wrapper beats hand-rolled state.

Option When it fits Cost When not to
Thin fetch wrapper Most apps, few dependencies You own retries/caching Heavy caching needs
TanStack Query + wrapper Lists, dashboards, refetching Library to learn Simple one-off forms
axios Teams used to interceptors Extra dependency; fetch now covers most needs New projects without a reason
Generated client (Kiota/NSwag) Large APIs Generated code to review Tiny APIs

Measure with Application Insights browser telemetry: failed dependency calls by status code, and cancelled requests on the server (OperationCanceledException count) to confirm aborts reach the backend.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions validation errors in the ProblemDetails errors dictionary Why: Checks they know where those validation errors come from on the server
    How to answer

    I validate input at the edge and business rules in the application or domain layer. For input, DataAnnotations ([Required], [Range], [StringLength]) and IValidatableObject on request DTOs are the baseline. In controllers, binding fills ModelState and [ApiController] returns a 400 ValidationProblemDetails before the action runs. In Minimal APIs on .NET 10, builder.Services.AddValidation() uses a source generator to validate parameters and return the same 400 ProblemDetails; before .NET 10 you needed a filter. FluentValidation is my choice for complex, conditional or async rules; I call it explicitly or from a filter, because its automatic MVC integration is deprecated. Business rules like stock levels or uniqueness are checked where the data lives and returned in the same error shape. The trade-off: attributes are simple and visible in OpenAPI; code-based validators are more expressive.

  2. When: Candidate mentions the server's CancellationToken Why: Checks they understand cooperative cancellation in .NET
    How to answer

    Cancellation in .NET is cooperative. A CancellationTokenSource owns the decision to cancel; it hands out CancellationTokens that code checks with IsCancellationRequested or ThrowIfCancellationRequested(), or passes to APIs that support it. When cancelled, the convention is to throw OperationCanceledException, which makes the task Canceled. Good APIs accept a CancellationToken as the last parameter (defaulting to default), pass it to every async call they make, and never swallow cancellation. In ASP.NET Core, a CancellationToken parameter is bound to HttpContext.RequestAborted, so client disconnects stop the work.

  3. When: Candidate mentions network errors or timeouts Why: Checks idempotency awareness from the client side
    How to answer

    Retry only idempotent requests: GET and HEAD are safe, PUT and DELETE are idempotent by definition (though a DELETE retry may return 404 the second time, so treat that as success). Retry on network errors, 408, 429 and 502–504, with exponential backoff and jitter, honouring Retry-After. Never blindly retry a POST or PATCH that creates or changes state unless the API supports an idempotency key header, or you risk duplicate orders or payments. Don't retry 4xx validation or auth errors. Cap attempts at 2–3 so a struggling backend isn't hammered.

↩ Usually asked after

More in Web Basics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me