ProblemDetails in ASP.NET Core .NET 10: the RFC 9457 shape (type, title, status, detail, instance, extensions), ValidationProblemDetails, AddProblemDetails and CustomizeProblemDetails, IProblemDetailsService and IProblemDetailsWriter, UseStatusCodePages for empty error responses, UseExceptionHandler and IExceptionHandler integration, adding traceId and stable error codes, and not leaking internals.
ProblemDetails is the standard JSON shape for HTTP API errors, defined by RFC 9457 (which replaced RFC 7807): type, title, status, detail, instance, plus extension members, served as application/problem+json. ValidationProblemDetails adds an errors dictionary per field. In ASP.NET Core, AddProblemDetails() registers IProblemDetailsService, which the framework uses wherever it writes an error body: UseExceptionHandler for unhandled exceptions, UseStatusCodePages for empty 404s/401s, and the developer exception page. CustomizeProblemDetails adds a traceId and anything else to every response; an IExceptionHandler maps known exceptions to specific codes with a stable errorCode extension. The trade-off: one consistent contract for every error, but you must make sure no internal detail leaks.
"ProblemDetails is the IETF standard for error bodies in HTTP APIs. RFC 7807 introduced it and RFC 9457 replaced it in 2023 with clarifications and a registry for common types. The body is
application/problem+jsonwithtype, a URI identifying the kind of problem,title,status,detailfor this occurrence,instance, and any extension members you need. For validation there's theValidationProblemDetailsvariant with anerrorsdictionary keyed by field name.In ASP.NET Core I call
builder.Services.AddProblemDetails(). That registersIProblemDetailsService, and from then on the framework writes ProblemDetails everywhere it produces an error:UseExceptionHandlerfor unhandled exceptions,UseStatusCodePagesfor responses that have an error status but no body, like a 404 from routing or a 401 from authentication,[ApiController]for validation and client errors, and .NET 10 Minimal API validation. InCustomizeProblemDetailsI add atraceIdfromActivity.Current?.Idand the request path asinstance, so a support person can paste the trace id into Application Insights and land on the exact request. For known failures I write anIExceptionHandlerthat maps, say,ConcurrencyExceptionto 409 with anerrorCodeoforder.concurrency_conflict, and returns false for anything else so the default handler produces a generic 500.For example, [at company] our [mobile app] parsed four different error shapes: HTML error pages from IIS, empty 404s, our own
{ success: false }JSON and ProblemDetails from validation. We standardised on ProblemDetails with stable error codes and a trace id, and [the app team deleted their per-endpoint error parsing and support tickets with 'unknown error' dropped noticeably]. The mistake I see is puttingexception.Messageindetailin production; that's how connection strings and SQL leak. The client gets a code and a trace id; the details stay in the logs."
| Member | Meaning | Example |
|---|---|---|
type |
URI identifying the problem type | https://errors.example.com.au/order/concurrency-conflict |
title |
Short, stable summary for the type | Order was modified by someone else |
status |
HTTP status code | 409 |
detail |
This occurrence, safe for clients | Reload the order and try again. |
instance |
This occurrence's URI | /orders/42 |
| extensions | Anything else | traceId, errorCode, errors |
| Source | Needs |
|---|---|
| Unhandled exception | UseExceptionHandler() + AddProblemDetails() (+ optional IExceptionHandler) |
| Empty 4xx/5xx (404, 401, 405) | UseStatusCodePages() + AddProblemDetails() |
| Invalid model (controllers) | [ApiController] |
| Invalid parameters (Minimal APIs, .NET 10) | AddValidation() |
| Your handlers | TypedResults.Problem(...), TypedResults.ValidationProblem(...), Problem() in controllers |
After adding traceId to every ProblemDetails, the median time for support to locate a failing request in Application Insights went from about 20 minutes of searching by time and user to under a minute, and a security review confirmed no exception messages or stack traces appeared in production responses.
Checks whether the candidate can design a consistent, safe error contract using the framework's built-in pieces.
Green flags
AddProblemDetails, UseExceptionHandler and UseStatusCodePages together.Red flags
AddProblemDetails()
├─ IProblemDetailsService (picks a writer and writes)
├─ IProblemDetailsWriter[] (default JSON writer; add your own for other formats)
└─ ProblemDetailsOptions.CustomizeProblemDetails (runs for every problem)
IProblemDetailsService.TryWriteAsync(new ProblemDetailsContext { HttpContext, ProblemDetails, Exception }) asks each writer CanWrite (based on the Accept header) and writes the first match. Framework components call this; you can too.
Request ─► UseExceptionHandler ─► ... ─► endpoint throws
│
▼
IExceptionHandler[] in registration order: TryHandleAsync → true stops the chain
│ (none handled)
▼
IProblemDetailsService writes a 500 ProblemDetails (no exception details outside Development)
UseExceptionHandler() without a path requires AddProblemDetails() or an IExceptionHandler, otherwise it throws at start-up. In Development, WebApplication adds the developer exception page automatically, which also writes ProblemDetails (including exception details) when the client accepts JSON.
UseStatusCodePages() hooks responses that finish with a status of 400–599 and no body (and haven't started). With AddProblemDetails() registered, it writes ProblemDetails; otherwise plain text. It doesn't touch responses that already have a body.
The framework fills type with links to the relevant RFC 9110 section for standard status codes (via ClientErrorMapping in MVC and the default writer), and title with the reason phrase. Your own problem types should have stable, documented URIs.
Use Activity.Current?.Id (the W3C traceparent id that Application Insights and OpenTelemetry use) with HttpContext.TraceIdentifier as a fallback. [ApiController] validation responses already include traceId; adding it in CustomizeProblemDetails makes every error consistent.
The Privacy Act's APP 11 and OWASP guidance both point the same way: error responses must not reveal personal information or internals. Stack traces, SQL text, server names and exception messages belong in logs, correlated by trace id.
UseStatusCodePages + AddProblemDetails and compare.CustomizeProblemDetails with traceId and find the request in Application Insights by that id.IExceptionHandler for a domain exception and check that other exceptions still produce a generic 500.Accept: application/xml and see which writer runs.Consistent ProblemDetails for exceptions, empty status codes and domain errors, with a trace id and stable error codes.
// Program.cs
using System.Diagnostics;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = ctx =>
{
// Every problem gets a trace id support can search for, and the request path
ctx.ProblemDetails.Extensions["traceId"] = Activity.Current?.Id ?? ctx.HttpContext.TraceIdentifier;
ctx.ProblemDetails.Instance ??= $"{ctx.HttpContext.Request.Method} {ctx.HttpContext.Request.Path}";
});
builder.Services.AddExceptionHandler<DomainExceptionHandler>(); // known exceptions -> specific codes
var app = builder.Build();
app.UseExceptionHandler(); // unhandled exceptions -> ProblemDetails (generic 500 if not handled above)
app.UseStatusCodePages(); // empty 404/401/405 -> ProblemDetails
app.MapPut("/orders/{id:int}", (int id) =>
id == 42 ? throw new ConcurrencyConflictException(id) : TypedResults.NoContent());
app.MapGet("/orders/{id:int}", (int id) => id > 1000
? TypedResults.Problem(title: "Order not found", statusCode: 404,
type: "https://errors.example.com.au/order/not-found",
extensions: new Dictionary<string, object?> { ["errorCode"] = "order.not_found" })
: Results.Ok(new { id }));
app.Run();
public sealed class ConcurrencyConflictException(int orderId) : Exception($"Order {orderId} was modified concurrently.")
{
public int OrderId { get; } = orderId;
}
public sealed class DomainExceptionHandler(IProblemDetailsService problems, ILogger<DomainExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext http, Exception exception, CancellationToken ct)
{
if (exception is not ConcurrencyConflictException conflict) return false; // let the default 500 handle it
logger.LogWarning(exception, "Concurrency conflict on order {OrderId}", conflict.OrderId);
http.Response.StatusCode = StatusCodes.Status409Conflict;
return await problems.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = http,
Exception = exception,
ProblemDetails = new ProblemDetails
{
Status = StatusCodes.Status409Conflict,
Type = "https://errors.example.com.au/order/concurrency-conflict",
Title = "Order was modified by someone else",
Detail = "Reload the order and try again.", // safe text, not exception.Message
Extensions = { ["errorCode"] = "order.concurrency_conflict" }
}
});
}
}
{
"type": "https://errors.example.com.au/order/concurrency-conflict",
"title": "Order was modified by someone else",
"status": 409,
"detail": "Reload the order and try again.",
"instance": "PUT /orders/42",
"errorCode": "order.concurrency_conflict",
"traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
}
exception.Message or stack traces in detail in production. Why it is wrong: It leaks SQL, connection details and personal data, and helps attackers. Instead: Safe, fixed text plus a trace id; details in logs.UseExceptionHandler() without AddProblemDetails() or a path. Why it is wrong: It throws at start-up (or writes nothing useful). Instead: Register AddProblemDetails().UseStatusCodePages. Why it is wrong: 404s from routing and 401s from authentication have empty bodies, so clients see a different shape. Instead: Add it so empty error responses become ProblemDetails.{ success, message } envelope from some handlers, HTML from the proxy. Why it is wrong: Every client needs several parsers and monitoring can't group errors. Instead: Route every error through IProblemDetailsService or TypedResults.Problem, and configure the proxy or gateway to pass API errors through.{ success: false }. Why it is wrong: Breaks HTTP semantics, caches, retries and monitoring; 'errors' look like successes in dashboards. Instead: Proper status codes with ProblemDetails.UseExceptionHandler to catch failures in BackgroundServices or message consumers. Why it is wrong: They run outside the request pipeline, so exceptions there are never turned into ProblemDetails and may stop the host. Instead: Catch, log with the trace id and retry or dead-letter in the worker itself.title for per-occurrence text. Why it is wrong: title should be stable per type; clients and dashboards group by it. Instead: Put occurrence details in detail.detail text to decide behaviour. Why it is wrong: Wording changes break clients. Instead: Provide a stable errorCode or type URI.Error responses are part of the API contract and deserve the same design care as success responses. A senior sets up the whole chain once (AddProblemDetails, UseExceptionHandler, UseStatusCodePages, CustomizeProblemDetails, a few IExceptionHandlers for known domain failures) so every endpoint gets consistent errors for free, documents the type URIs and errorCode values, and makes the trace id the bridge between a client's error and the logs. Measure success by fewer 'unknown error' tickets and faster incident triage.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Framework defaults (AddProblemDetails) |
Every API | None | Never skip |
CustomizeProblemDetails (traceId, instance) |
Every API | Trivial | n/a |
IExceptionHandler per domain exception family |
Known failures with meaningful codes | Mapping code | Control flow for expected outcomes (prefer results) |
Result types returning TypedResults.Problem |
Expected business failures | Slightly more code | Truly exceptional conditions |
| Custom error envelope | Legacy clients that can't change | Non-standard, more docs | New APIs |
In ASP.NET Core, register AddProblemDetails(), one or more IExceptionHandler implementations (.NET 8+) with AddExceptionHandler<T>(), and app.UseExceptionHandler() early in the pipeline. Handlers log once and map known exceptions to the right status code and an RFC 9457 ProblemDetails body, and never leak stack traces in production. For the process as a whole, AppDomain.CurrentDomain.UnhandledException is a last-chance notification: you can log and flush, but the process still terminates. TaskScheduler.UnobservedTaskException fires when a faulted task that nobody awaited is garbage-collected; it does not crash the process by default. In a BackgroundService, an unhandled exception in ExecuteAsync stops the host by default (.NET 6+). async void exceptions go to the synchronisation context and usually crash the process, so avoid async void except for event handlers.
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.
How to tell it (STAR)
**S:** Our [mobile API] returned four different error shapes and a scan found a SQL error message leaking in a 500. **T:** I owned standardising errors without breaking older app versions. **A:** I removed the leak first, then wired AddProblemDetails, UseExceptionHandler with a few IExceptionHandlers, and UseStatusCodePages, added trace ids and stable error codes, and added contract tests for every non-2xx response. **R:** The app team removed per-endpoint error parsing, 'unknown error' tickets [dropped by about half], and support could find any failing request by trace id in under a minute.
Last updated 23 Nov 2026.