In an ASP.NET Core 10 API with controllers and Minimal APIs, how does IProblemDetailsService pick an IProblemDetailsWriter, and why might a custom writer never run?
answer
- first CanWrite wins
- writers run in registration order
- AddControllers adds an MVC writer
- TryWriteAsync returns false, WriteAsync throws
- writers are captured by a singleton
basics
~10 sProblemDetailsService asks each registered IProblemDetailsWriter in registration order and lets the first whose CanWrite returns true write. A custom writer registered after AddControllers() or AddProblemDetails() is never reached for requests an earlier writer claims.
solid answer
~40 s`ProblemDetailsService` is a singleton that copies the registered `IProblemDetailsWriter` services into an array when it is built. `TryWriteAsync` walks that array in registration order, calls `WriteAsync` on the first writer whose `CanWrite` returns `true`, and returns `true`; if none accepts, it returns `false`, and `WriteAsync` throws `InvalidOperationException`. `AddProblemDetails()` adds `DefaultProblemDetailsWriter`, which accepts JSON-compatible `Accept` headers. `AddControllers()` adds MVC's `DefaultApiProblemDetailsWriter`, which claims any endpoint carrying `[Controller]` metadata, and for one without `[ApiController]` writes nothing while still counting as handled. So a custom writer must be registered before both calls; the docs spell this out for `AddControllers()` and the other MVC registrations. It must also be safe as a singleton: resolve scoped services from `context.HttpContext.RequestServices`, never through its constructor.
code
csharp · 21 linespublic sealed class BankProblemWriter : IProblemDetailsWriter
{
public bool CanWrite(ProblemDetailsContext context) =>
context.HttpContext.Request.Path.StartsWithSegments("/api");
public ValueTask WriteAsync(ProblemDetailsContext context)
{
var problem = context.ProblemDetails;
problem.Status ??= context.HttpContext.Response.StatusCode;
problem.Extensions["traceId"] =
Activity.Current?.Id ?? context.HttpContext.TraceIdentifier;
return new ValueTask(context.HttpContext.Response.WriteAsJsonAsync(
problem, problem.GetType(), options: null, contentType: "application/problem+json"));
}
}
// Program.cs: before AddControllers() and AddProblemDetails()
builder.Services.AddSingleton<IProblemDetailsWriter, BankProblemWriter>();
builder.Services.AddControllers();
builder.Services.AddProblemDetails();go deeper
Recall that several writers can be registered and that the service lets the first willing one write the body.
Explain CanWrite on the two built-in writers, registration order, and the difference between WriteAsync and TryWriteAsync.
Diagnose an empty 500 from a non-API controller, a custom writer that never fires, and a scoped writer captured by the singleton service.
Decide whether a service needs a custom writer at all or only the callback, and how to keep registration order from becoming a hidden contract.
## How the service chooses `IProblemDetailsService` has two members, and the default implementation is short: 1. The constructor receives `IEnumerable<IProblemDetailsWriter>` and stores it as an array, in **registration order**. 2. `TryWriteAsync(context)` loops over the array; the **first** writer whose `CanWrite(context)` returns `true` gets `WriteAsync(context)`, and the method returns `true` without asking the rest. 3. If no writer accepts, `TryWriteAsync` returns `false`. 4. `WriteAsync(context)` calls `TryWriteAsync` and throws `InvalidOperationException` ("Unable to find a registered `IProblemDetailsWriter` that can write to the given context.") on `false`. There is no scoring and no content negotiation between writers: order decides. ## The two built-in writers | Writer | Registered by | `CanWrite` | What `WriteAsync` does | |---|---|---|---| | `DefaultProblemDetailsWriter` | `AddProblemDetails()` | no `Accept`, a JSON or problem+json type, or a wildcard | applies defaults, adds `traceId`, runs `CustomizeProblemDetails`, writes `application/problem+json` with the Minimal API `JsonOptions` | | `DefaultApiProblemDetailsWriter` | `AddControllers()` and the other MVC registrations | the endpoint (or the failing endpoint's metadata) carries `[Controller]` | if there is no `[ApiController]` or `SuppressMapClientErrors` is set, writes nothing; otherwise rebuilds the body with `ProblemDetailsFactory` and picks an output formatter for problem+json or problem+xml | Two consequences surprise people: - With `AddControllers()` called first, the MVC writer is first. An exception in a controller action reaches it, so the body follows MVC's formatters and `ClientErrorMapping`, not the JSON options of the Minimal API side. - For a controller without `[ApiController]`, the MVC writer accepts and writes nothing. `TryWriteAsync` still returns `true`, so the exception handler treats the exception as handled and the client gets an empty 500. ## Why a custom writer never runs - **It was registered too late.** `AddSingleton<IProblemDetailsWriter, BankProblemWriter>()` after `AddControllers()` and `AddProblemDetails()` puts it third; the earlier writers claim every JSON client and every controller endpoint first. The docs require it before `AddControllers()`, `AddControllersWithViews()`, `AddRazorPages()` or `AddMvc()`. - **Its `CanWrite` is too narrow**, for example matching an exact `Accept` string while browsers and HTTP clients send lists and wildcards. - **Nothing calls the service.** A `ProblemDetails` returned through `Results.Json` or `Ok()` never reaches any writer. ## Lifetime of a writer `ProblemDetailsService` is a singleton and captures its writers once, so a writer behaves as a singleton whatever lifetime you give it. Registering one as scoped makes it, and its scoped dependencies, captive; in Development, where `WebApplicationBuilder` turns on scope validation and build-time validation, the app fails at startup because a singleton consumes a scoped service. Register writers as singletons and take per-request services from `context.HttpContext.RequestServices`. ## Finding out which writer ran 1. List the writers in the order the service will try them: `app.Services.GetServices<IProblemDetailsWriter>()` returns them in registration order. 2. Read the response `Content-Type`: `application/problem+json` with `traceId` points at the default writer or MVC's JSON formatter; `application/problem+xml` can only come from MVC's writer with XML formatters registered. 3. Check the request's `Accept` header; a client library that sends a narrow custom type is declined by the default writer. 4. Check the endpoint: a controller endpoint is claimed by MVC's writer when it is earlier in the list, a Minimal API endpoint never is. ## When every writer declines The caller decides what the client gets: - `Results.Problem` and `Results.ValidationProblem` serialize the body themselves as JSON, without `traceId` or the callback. - Status-code pages write their plain-text `Status Code: 404; Not Found` line. - The exception handler middleware leaves the 500 with an empty body. - MVC's 406 path leaves the 406 empty. A team that wants one body for every client either accepts more media types in a custom writer or makes sure clients send a JSON-compatible `Accept`.
- A non-[ApiController] MVC controller throws and the client gets an empty 500 although AddProblemDetails() is registered. Why?With `AddControllers()` registered first, `DefaultApiProblemDetailsWriter` is first in the list. Its `CanWrite` only checks for `[Controller]` metadata, so it claims the request, then writes nothing because the endpoint lacks `[ApiController]`. `TryWriteAsync` still returns `true`, so the exception handler counts the exception as handled. Add `[ApiController]`, or register `AddProblemDetails()` first so the default writer claims JSON clients.
- Should your own middleware call IProblemDetailsService.WriteAsync or TryWriteAsync?`TryWriteAsync`, whenever a client might refuse JSON. `WriteAsync` throws `InvalidOperationException` when no writer accepts the request, which turns an error response into a second exception. With `TryWriteAsync` you get `false` and can write a plain-text or empty fallback yourself.
A taxi rank: the first cab in the queue that agrees to the destination takes the fare, even if a better-suited cab waits behind it. Writers are tried in the order they joined the queue, and the first willing one writes.
- IProblemDetailsService picks the writer whose media type best matches the Accept header.
- A custom IProblemDetailsWriter runs first no matter where it is registered.
- Registering a writer with AddScoped gives it a fresh instance per request.
- When no writer accepts, TryWriteAsync throws InvalidOperationException.
- DefaultApiProblemDetailsWriter only claims endpoints that carry [ApiController].