skip to content

In ASP.NET Core 10, what does AddProblemDetails() register, and what body does an API then send for an error that has no body?

level: juniorimportance: must knowfreq 68%

answer

  1. one service, many callers
  2. singleton IProblemDetailsService plus a default writer
  3. the Accept header decides CanWrite
  4. type points at an RFC 9110 section
  5. traceId from Activity.Current or TraceIdentifier

basics

~10 s

AddProblemDetails() registers IProblemDetailsService and a default writer as singletons. The exception handler, status-code pages, developer exception page and Problem results then write an application/problem+json body with type, title, status and a traceId.

solid answer

~40 s

`builder.Services.AddProblemDetails()` registers `IProblemDetailsService` as a singleton, adds `DefaultProblemDetailsWriter` as an `IProblemDetailsWriter`, and puts a source-generated `ProblemDetails` JSON context into the Minimal API `JsonOptions`. By itself it changes nothing; the components that look the service up use it. `UseExceptionHandler()` without a path writes a 500 body, `UseStatusCodePages()` fills an empty 400-599 response, the developer exception page answers non-HTML clients, and `Results.Problem` / `Results.ValidationProblem` write through it. The default writer fills a missing `status` from the response, gives the common statuses an RFC 9110 `type` URI and a `title`, and adds `traceId` = `Activity.Current?.Id ?? HttpContext.TraceIdentifier`. It writes only when `Accept` allows JSON: `application/json`, `application/problem+json`, a wildcard, or no header. The `dotnet new webapi` template does not call it.

code

csharp · 17 lines
csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddProblemDetails();
builder.Services.AddControllers();

var app = builder.Build();

app.UseExceptionHandler();   // writes 500 bodies through IProblemDetailsService
app.UseStatusCodePages();    // fills empty 400-599 responses the same way

app.MapGet("/api/accounts/{id:int}", (int id) =>
    id == 42
        ? Results.Ok(new { id, balance = 120.50m })
        : Results.Problem(statusCode: 404, detail: $"Account {id} does not exist."));

app.MapControllers();
app.Run();

go deeper

for a junior

Recall that AddProblemDetails registers a service other components use, and list the members a default body carries: type, title, status and traceId.

for a middle

Explain which components consult IProblemDetailsService, how CanWrite reads the Accept header, and why MVC controllers produce bodies without the service.

for a senior

Show you know what each caller does when the writer declines, why browsers still get JSON, and that the webapi template wires none of this for you.

for a principal

Frame the registration as a one-line way to make every surface of a service fail in one shape, and weigh where a custom writer or callback earns its keep.

## What the call registers `AddProblemDetails()` is an extension method on `IServiceCollection` (class `ProblemDetailsServiceCollectionExtensions`). It adds three things and nothing else: - **`IProblemDetailsService`** mapped to the internal `ProblemDetailsService`, registered with `TryAddSingleton`, so calling it twice still leaves one **singleton**. - **`IProblemDetailsWriter`** mapped to `DefaultProblemDetailsWriter`, a singleton added with `TryAddEnumerable`, so other writers can sit beside it. - An `IConfigureOptions<JsonOptions>` that inserts a source-generated `ProblemDetailsJsonContext` at the head of the Minimal API serializer's resolver chain, so `ProblemDetails` serializes without reflection, which also keeps it working under Native AOT. An overload takes `Action<ProblemDetailsOptions>`, whose only property is `CustomizeProblemDetails`. The service exposes `WriteAsync`, which throws `InvalidOperationException` when no writer accepts the request, and `TryWriteAsync`, which returns `false` instead. ## Who uses the service Registering the service does not catch anything. Framework components ask DI for `IProblemDetailsService` and use it when it is there: | Component | Without `AddProblemDetails()` | With it | |---|---|---| | `UseExceptionHandler()` with no path or delegate | building the pipeline throws `InvalidOperationException` | a 500 ProblemDetails body | | `UseStatusCodePages()` | `text/plain` "Status Code: 404; Not Found" | ProblemDetails with that status | | Developer exception page, non-HTML client | plain-text exception dump | ProblemDetails with an `exception` extension | | `Results.Problem`, `Results.ValidationProblem` | JSON written directly, no `traceId` | written by the service | | MVC's 406 when no formatter matches | empty 406 | a 406 ProblemDetails body | MVC controllers are the exception: `ControllerBase.Problem()` and the `[ApiController]` error results go through `ProblemDetailsFactory`, which `AddControllers()` registers on its own. ## The default body For a banking API with `UseStatusCodePages()`, a request to an unknown route such as `/api/acounts/7` gets: ```json { "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5", "title": "Not Found", "status": 404, "traceId": "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" } ``` - The **`ProblemDetails`** class lives in the `Microsoft.AspNetCore.Mvc` namespace although it ships with the HTTP abstractions; its `Type`, `Title`, `Status`, `Detail` and `Instance` properties are skipped when null. - **`Extensions`** is a dictionary marked `[JsonExtensionData]`, so each entry is written as a top-level member, which is how `traceId` appears beside `status`. - `DefaultProblemDetailsWriter.WriteAsync` copies `status` from `HttpResponse.StatusCode` when the body has none, then fills `title` and `type` from an internal table: RFC 9110 section URIs for the common 4xx and 5xx codes, and the title "An error occurred while processing your request." for 500. - **`traceId`** is `Activity.Current?.Id` (the W3C form `00-<trace id>-<span id>-<flags>`) and falls back to `HttpContext.TraceIdentifier`; its key follows the JSON naming policy. - `CustomizeProblemDetails` runs after those defaults, so it can change any of them. ## When the writer declines `DefaultProblemDetailsWriter.CanWrite` reads the request's `Accept` header: 1. No `Accept` header: it writes. 2. A value that is `application/json` or `application/problem+json` (parameters allowed): it writes. 3. A wildcard such as `*/*` or `application/*`: it writes, whatever the `q` weight. 4. Anything else, for example only `text/html`: it declines and `TryWriteAsync` returns `false`. Each caller then uses its own fallback: status-code pages write their plain-text line, `Results.Problem` serializes the object itself, and the exception handler leaves an empty 500. ## Seeing it work Four requests against the banking API show the whole behaviour: 1. An unknown path with no `Accept` header: the four-member body above, sent as `application/problem+json`. 2. The same path with only `Accept: text/html`: the same 404 now carries the plain-text status line, because the default writer declined. 3. An endpoint that throws, outside Development, with `UseExceptionHandler()` registered: a 500 body with the generic 500 title, a `traceId` and no `detail`, so no exception text leaves the server. 4. The same throw in Development when, as the MVC and Razor Pages templates do, `UseExceptionHandler` is registered only outside Development: `WebApplication` has already put the developer exception page first, and a JSON client gets a ProblemDetails whose `title` is the exception type, `detail` its message, and an `exception` extension with the stack trace, headers, path, endpoint and route values. That body belongs on a developer's machine only. The `traceId` in step 3 is what support staff paste into a log search to find the matching server-side entry. ## What it does not do - It does not catch exceptions; an exception only becomes a body when exception-handling middleware runs. - It does not rewrite a response that already has a body or a `Content-Type`. - It is not in the `dotnet new webapi` template, which wires no error middleware, so outside Development a new API answers exceptions and unmatched routes with empty bodies until you add it.

  • Why does a browser that hits a missing URL get JSON, not a text page, once AddProblemDetails() is registered?
    Browsers usually end their `Accept` header with `*/*` at a lower `q` weight. `DefaultProblemDetailsWriter.CanWrite` accepts any value that is a wildcard covering `application/json`, and media-type matching ignores the `q` parameter, so the writer claims the request. Only a client whose `Accept` lists nothing JSON-compatible, such as `text/html` alone, falls back to the plain-text status page.
  • Does AddProblemDetails() change what ControllerBase.Problem() returns in an MVC controller?
    Mostly not: `ControllerBase.Problem()` builds its body with MVC's own `ProblemDetailsFactory`, registered by `AddControllers()`, which already fills `type`, `title` and `traceId`. What `AddProblemDetails(options => ...)` adds is a `CustomizeProblemDetails` callback, and the default factory reads that callback too, so customizations reach controllers and Minimal APIs alike.
  • What happens if your code calls IProblemDetailsService.WriteAsync for a request whose Accept header is only text/html?
    `WriteAsync` loops over the registered writers, none returns `true` from `CanWrite`, and it throws `InvalidOperationException` ("Unable to find a registered `IProblemDetailsWriter` that can write to the given context"). Call `TryWriteAsync` instead when a client might refuse JSON; it returns `false` and lets you write a fallback response yourself.

  • In production, AddProblemDetails() alone turns unhandled exceptions into ProblemDetails, with no UseExceptionHandler.
  • The dotnet new webapi template already calls AddProblemDetails() for you.
  • AddProblemDetails() registers IProblemDetailsService as scoped, one instance per request.
  • The traceId member holds HttpContext.Connection.Id, so it identifies the client connection.
  • With only text/html in Accept, the default writer renders the ProblemDetails as an HTML page.