skip to content

In an ASP.NET Core 10 API, how do you use CustomizeProblemDetails to stamp every error body, and which responses does the callback reach?

level: middleimportance: must knowfreq 55%

answer

  1. one callback, two code paths
  2. ProblemDetailsOptions.CustomizeProblemDetails
  3. runs after defaults and traceId
  4. ProblemDetailsContext.Exception is often null
  5. DefaultProblemDetailsFactory reads it too

basics

~10 s

Pass an Action<ProblemDetailsContext> to AddProblemDetails(options => options.CustomizeProblemDetails = ...). It runs after the defaults on every body IProblemDetailsService's default writer or MVC's DefaultProblemDetailsFactory builds, but not on JSON you serialize yourself.

solid answer

~40 s

Register it with `builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = ctx => { ... })`. The callback receives a `ProblemDetailsContext`: `HttpContext`, the mutable `ProblemDetails`, the `Exception` when the exception handler or developer page produced the body, and `AdditionalMetadata` from the failing endpoint. Two code paths call it. `DefaultProblemDetailsWriter` calls it after filling `type`, `title`, `status` and `traceId` whenever it is the writer chosen, which covers the exception handler, status-code pages, `Results.Problem` / `Results.ValidationProblem` and, in .NET 10, the built-in Minimal API validation. MVC's `DefaultProblemDetailsFactory` calls it too, for `ControllerBase.Problem()`, `ValidationProblem()` and the `[ApiController]` error bodies. It does not see a `ProblemDetails` you hand to `Results.Json` or `WriteAsJsonAsync`, nor any `Results.Problem` body written when the service is missing or every writer declines.

code

csharp · 16 lines
csharp
builder.Services.AddProblemDetails(options =>
{
    options.CustomizeProblemDetails = ctx =>
    {
        ctx.ProblemDetails.Extensions["service"] = "accounts-api";

        var exception = ctx.Exception
            ?? ctx.HttpContext.Features.Get<IExceptionHandlerFeature>()?.Error;

        if (exception is not null &&
            ctx.HttpContext.RequestServices.GetRequiredService<IHostEnvironment>().IsDevelopment())
        {
            ctx.ProblemDetails.Detail = exception.Message;
        }
    };
});

go deeper

for a junior

Recall that CustomizeProblemDetails is set through AddProblemDetails and receives a ProblemDetailsContext whose ProblemDetails you edit.

for a middle

Explain the two code paths that invoke the callback, that it runs after the defaults, and which bodies never reach it.

for a senior

Show the production judgment: environment-gated detail, per-request services resolved from HttpContext, and the null Exception on the MVC writer path.

for a principal

Argue for one callback as the single place a multi-surface service shapes its errors, and say when a custom writer would be worth its extra surface.

## The registration `ProblemDetailsOptions` has one property, **`CustomizeProblemDetails`**, of type `Action<ProblemDetailsContext>?`. You set it through the `AddProblemDetails` overload that takes a configure delegate, which also registers `IProblemDetailsService`. Setting it with `Configure<ProblemDetailsOptions>` alone fills the option but registers no `IProblemDetailsService`, so only MVC's factory runs it and the middleware-side callers never do. `ProblemDetailsContext` carries: - **`HttpContext`**: the request, its `RequestServices`, method and path. - **`ProblemDetails`**: the body about to be written; mutate it in place or replace it. - **`Exception`**: set by the exception handler middleware and the developer exception page, null everywhere else. - **`AdditionalMetadata`**: the failing endpoint's metadata when the exception handler supplies it, otherwise null. ## The two paths that run it | Path | Who uses it | When the callback runs | |---|---|---| | `DefaultProblemDetailsWriter` | exception handler, status-code pages, developer page, `Results.Problem` / `TypedResults.Problem`, `Results.ValidationProblem`, built-in Minimal API validation in .NET 10 | after defaults and `traceId`, just before serializing | | MVC's `DefaultProblemDetailsFactory` | `ControllerBase.Problem()`, `ValidationProblem()`, the `[ApiController]` automatic 400 and client-error bodies | after `ClientErrorMapping` and `traceId` are applied | Because both paths invoke the same delegate, a banking API that mixes controllers and Minimal API endpoints gets one body shape from one callback. The order matters: the callback runs **after** the defaults, so whatever it writes wins, including a `traceId` you overwrite by accident. ## What it does not reach 1. A `ProblemDetails` you serialize yourself with `Results.Json`, `Ok(problem)` or `Response.WriteAsJsonAsync`: no service is involved. 2. `Results.Problem` when `AddProblemDetails()` was never called: `ProblemHttpResult` falls back to writing the JSON directly, with defaults but no `traceId` and no callback. 3. `Results.Problem` for a client whose `Accept` header has nothing JSON-compatible: every writer declines, and the same direct-JSON fallback runs. 4. A body a custom `IProblemDetailsWriter` writes, unless that writer calls the option itself. ## A worked example The banking API stamps `instance` with the method and path, and adds the exception message only in Development: ```csharp builder.Services.AddProblemDetails(options => { options.CustomizeProblemDetails = ctx => { var request = ctx.HttpContext.Request; ctx.ProblemDetails.Instance = $"{request.Method} {request.Path}"; var env = ctx.HttpContext.RequestServices.GetRequiredService<IHostEnvironment>(); if (ctx.Exception is not null && env.IsDevelopment()) { ctx.ProblemDetails.Detail = ctx.Exception.Message; } }; }); ``` - The production 500 body keeps the default title and no `detail`, so nothing of the exception leaves the server. - The callback is a plain delegate on a singleton options object; resolve per-request services from `ctx.HttpContext.RequestServices` inside it rather than capturing them. ## The callback against the other hooks | Hook | Reaches | Use it for | |---|---|---| | `CustomizeProblemDetails` | default writer and MVC's factory | adding or overriding members on every body | | Custom `IProblemDetailsWriter` | only requests its `CanWrite` claims | another media type, serializer or claim rule | | Subclass of `ProblemDetailsFactory` | MVC only | controller-specific construction | | An `IExceptionHandler` that builds its own `ProblemDetails` and calls `IProblemDetailsService.TryWriteAsync` | exceptions only | per-exception status, `title` and `detail` | The last row composes with the callback: a handler that writes through the service still gets the defaults, `traceId` and your callback on top of the members it set. A handler that serializes its own object with `WriteAsJsonAsync` skips all three, which is the usual reason one exception type answers with a body that looks different from the rest. ## The null Exception trap `ctx.Exception` is null more often than people expect: - Every body from `Results.Problem`, `ValidationProblem` or status-code pages has no exception. - When `AddControllers()` is registered **before** `AddProblemDetails()`, MVC's `DefaultApiProblemDetailsWriter` sits first in the writer list. For an exception thrown by a controller action it claims the body, rebuilds it through `ProblemDetailsFactory` and calls the callback with a fresh context that has no `Exception`. When you need the exception there, read `IExceptionHandlerFeature` from `ctx.HttpContext.Features`, which the exception handler middleware sets before any body is written.

  • Why is ctx.Exception null in the callback for an exception thrown by an [ApiController] action?
    If `AddControllers()` ran before `AddProblemDetails()`, MVC's `DefaultApiProblemDetailsWriter` is first in the writer list and claims any controller endpoint. It rebuilds the body through `ProblemDetailsFactory`, whose callback call passes a new context with only `HttpContext` and `ProblemDetails`. Read `IExceptionHandlerFeature.Error` from `HttpContext.Features` instead, or register `AddProblemDetails()` first.
  • When would you choose a custom IProblemDetailsWriter over CustomizeProblemDetails?
    When the change is about how or whether the body is written rather than its members: a different media type, a different serializer, or claiming only some requests through `CanWrite`. Editing members such as `instance`, `detail` or an extension is what `CustomizeProblemDetails` is for, and it also reaches MVC's factory, which a custom writer does not.

  • CustomizeProblemDetails only affects Minimal APIs; ControllerBase.Problem() ignores it.
  • The callback also edits a ProblemDetails returned through Results.Json(problem).
  • ctx.Exception is always set, so the callback can switch on the exception type.
  • The callback runs before the defaults, so a traceId it sets is overwritten.
  • Configure<ProblemDetailsOptions>() alone registers IProblemDetailsService for the middleware.

Assumes ASP.NET Core 10, where the built-in Minimal API validation (AddValidation) writes its 400 body through IProblemDetailsService, so CustomizeProblemDetails reaches it.