skip to content

In an ASP.NET Core typed client, what do GetFromJsonAsync and HttpClient.Timeout do when the downstream API answers 404 or answers too slowly?

level: middleimportance: should knowfreq 44%

answer

  1. success check built in
  2. HttpRequestException.StatusCode
  3. Timeout defaults to 100 seconds
  4. TaskCanceledException wrapping TimeoutException
  5. pass the request's CancellationToken

basics

~10 s

GetFromJsonAsync checks the status and throws HttpRequestException, with StatusCode set, on a 404. If no answer arrives within HttpClient.Timeout, 100 seconds by default, the call throws TaskCanceledException whose inner exception is a TimeoutException.

solid answer

~40 s

`GetFromJsonAsync<T>` from `System.Net.Http.Json` sends a GET, calls the success check for you and deserializes the body with System.Text.Json's web defaults (camelCase, case-insensitive). A 404 or 500 therefore surfaces as an `HttpRequestException` whose `StatusCode` property holds the status, not as a null result; if a 404 is a normal answer, call `GetAsync`, inspect the status and only then `ReadFromJsonAsync<T>`. `HttpClient.Timeout` defaults to 100 seconds and bounds the whole send, including every delegating handler in the chain; you set it per client in the `AddHttpClient` configuration delegate. When it fires, the call throws `TaskCanceledException` with an inner `TimeoutException`; when your own `CancellationToken` fires, for example the request's abort token, it throws `TaskCanceledException` without that inner exception, which is how you tell the two apart.

code

csharp · 19 lines
csharp
public sealed class ShippingRatesClient(HttpClient http, ILogger<ShippingRatesClient> log)
{
    public async Task<RateQuote?> TryGetQuoteAsync(string zip, CancellationToken ct)
    {
        try
        {
            return await http.GetFromJsonAsync<RateQuote>($"v2/quotes?zip={zip}", ct);
        }
        catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
        {
            return null; // unknown postcode
        }
        catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
        {
            log.LogWarning("Shipping rates timed out for {Zip}", zip);
            return null;
        }
    }
}

go deeper

for a junior

Recall that GetFromJsonAsync throws HttpRequestException on an error status and that HttpClient.Timeout is 100 seconds unless you change it.

for a middle

Explain how to tell a timeout from caller cancellation, when to switch to GetAsync plus ReadFromJsonAsync, and where to configure Timeout per client.

for a senior

Show you size Timeout against the caller's budget, propagate RequestAborted and keep retries inside the overall limit.

for a principal

Decide how downstream failures map to your own API's responses and fallbacks, and which timeouts each team owns.

## What GetFromJsonAsync does `GetFromJsonAsync<T>` is an extension method on `HttpClient` from the `System.Net.Http.Json` namespace, part of the shared framework. In one call it: 1. sends a GET to the given URI (relative to `BaseAddress` when one is configured); 2. checks the response status, the same check `EnsureSuccessStatusCode` performs; 3. deserializes the body into `T` with `System.Text.Json`, using `JsonSerializerDefaults.Web` (camelCase property names, case-insensitive matching, numbers allowed as strings) unless you pass your own `JsonSerializerOptions` or a source-generated `JsonTypeInfo<T>`. The return type is `Task<T?>`: a JSON `null` body gives you `null`, but an error status never does. Its siblings follow the same pattern: `PostAsJsonAsync` and `PutAsJsonAsync` serialize a body, `ReadFromJsonAsync<T>` reads one from an `HttpResponseMessage` you already have, and `GetFromJsonAsAsyncEnumerable<T>` streams a JSON array item by item. ## Error statuses In a web shop's typed client for a shipping-rates provider, a 404 for an unknown postcode is a business answer, not a crash. With `GetFromJsonAsync` it arrives as an exception: - the type is `HttpRequestException`; - its `StatusCode` property is set (`HttpStatusCode.NotFound`), so a `catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)` filter can handle it; - the response body, which may hold a problem-details document, is not available. When the status is meaningful, use the two-step form instead: `var response = await http.GetAsync(uri, ct);`, branch on `response.StatusCode`, then `await response.Content.ReadFromJsonAsync<T>(ct)` on success. That also lets you read an error body. ## HttpClient.Timeout `HttpClient.Timeout` is the overall time a single send may take: - **Default:** 100 seconds. - **Scope:** it is enforced by `HttpClient` around the whole handler chain, so a slow `DelegatingHandler` or a handler that sends several attempts all count against the same budget. - **Where to set it:** in the `AddHttpClient` configuration delegate, `client.Timeout = TimeSpan.FromSeconds(15)`, so every client created for that name gets it. `Timeout.InfiniteTimeSpan` disables it. - **What it throws:** a `TaskCanceledException` (an `OperationCanceledException`) whose `InnerException` is a `TimeoutException`. | Cause | Exception you catch | Distinguishing detail | |---|---|---| | Error status from `GetFromJsonAsync` | `HttpRequestException` | `StatusCode` is set | | Connection refused, DNS failure, TLS failure | `HttpRequestException` | `StatusCode` is null | | `HttpClient.Timeout` elapsed | `TaskCanceledException` | `InnerException is TimeoutException` | | Your `CancellationToken` was cancelled | `TaskCanceledException` | no `TimeoutException` inside | ## Cancellation from the incoming request In a Minimal API handler or controller action, accept a `CancellationToken` parameter (bound to `HttpContext.RequestAborted`) and pass it to `GetFromJsonAsync`. If the shopper closes the browser, the outgoing call is cancelled too instead of running to the 100-second limit. Catch that case separately from a timeout: the former is the caller leaving, the latter is the downstream being slow. ## Serializer options and trimming The JSON helpers take an optional `JsonSerializerOptions` or a `JsonTypeInfo<T>`: - Pass `JsonSerializerOptions` when the provider uses a different naming policy, such as snake_case property names, or needs custom converters. - Pass a `JsonTypeInfo<T>` from a source-generated `JsonSerializerContext` when the app is trimmed or published as Native AOT, where reflection-based serialization is not available; the call becomes `GetFromJsonAsync(uri, RatesJsonContext.Default.RateQuote, ct)`. ## Turning failures into results A typed client is the natural place to translate transport failures into something the rest of the shop understands. Rather than letting `HttpRequestException` and `TaskCanceledException` escape into controllers, the client can return a small result type (a quote, "unknown postcode" or "provider unavailable") and log the technical detail once. Callers then decide on a fallback, such as a flat shipping rate, without knowing anything about HTTP status codes or timeout exceptions. Keep caller cancellation out of that translation: when the request's token fires, let the `OperationCanceledException` propagate, because nobody is waiting for the answer any more. ## Picking a value - Keep `Timeout` shorter than the time your own callers will wait, or the shop's page times out before your code can fall back to a cached rate. - If you add retry handlers, remember that `Timeout` still caps the sum of all attempts; per-attempt limits are configured in the resilience handler, not here. - Do not lower `Timeout` to work around a captured client or a stale connection; those are lifetime problems, not timing ones.

  • How do you read the provider's error body when it answers 422 with a problem-details document?
    Do not use `GetFromJsonAsync`, which throws before you can see the body. Call `GetAsync`, check `response.IsSuccessStatusCode`, and on failure read the body with `response.Content.ReadFromJsonAsync<ProblemDetails>(ct)` or as a string, then map it to your own result type.
  • Where would you set a 15-second timeout for every shipping-rates call?
    In the registration: `builder.Services.AddHttpClient<ShippingRatesClient>(c => c.Timeout = TimeSpan.FromSeconds(15))`. The delegate runs for each client the factory creates for that name, so every typed client instance starts with the same timeout and no call site has to remember it.

  • Expects GetFromJsonAsync to return null on a 404
  • Believes HttpClient.Timeout defaults to 30 seconds
  • Treats every TaskCanceledException as a timeout
  • Thinks HttpClient.Timeout applies to each retry attempt separately
  • Leaves out the request's CancellationToken on outgoing calls