Structured Validation and ProblemDetails in ASP.NET Core: Consistent 400s Across Controllers

An API that returns a JSON object for a validation failure, a plain string for a not-found, and an HTML stack trace for a server fault has three error formats. Your clients have to parse all three. They will get one of them wrong.

ASP.NET Core has shipped a single, standard error shape for years — ProblemDetails, aligned with RFC 9457 (the 2023 revision that obsoletes RFC 7807). The problem is not that the shape is missing. It is that the framework produces it through more than one internal pipeline, and most codebases only wire up one of them. So model-binding failures come out one way, your thrown exceptions another, and a raw 404 from the routing layer a third. This is a guide to making every non-2xx response — validation, not-found, conflict, or an unhandled fault — emit the same application/problem+json body, on .NET 9 with controllers.

One shape, defined once

A ProblemDetails body is five well-known members — type, title, status, detail, instance — plus any extension members you add. A validation error uses the specialised ValidationProblemDetails, which adds an errors dictionary keyed by field. The goal is that a client can read status and, if it is a 400, read errors, and never has to branch on which part of your stack failed.

Free · 4 minutes

If your most senior engineer left tomorrow, would anyone still understand the system?

Fourteen questions on documentation, dependencies, and the gap between how the architecture works and how many people know it. Banded finding on screen, full sheet by email.

Start by turning the service on and adding one enrichment — a trace identifier — so every problem is traceable back to a log line:

using System.Diagnostics;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddProblemDetails(options =>
{
    options.CustomizeProblemDetails = ctx =>
    {
        ctx.ProblemDetails.Instance ??=
            $"{ctx.HttpContext.Request.Method} {ctx.HttpContext.Request.Path}";
        ctx.ProblemDetails.Extensions["traceId"] =
            Activity.Current?.Id ?? ctx.HttpContext.TraceIdentifier;
    };
});

builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddControllers();

var app = builder.Build();

app.UseExceptionHandler();   // no path argument: the IExceptionHandler runs
app.UseStatusCodePages();    // gives a bare 404/405/406 a problem body too
app.MapControllers();
app.Run();

UseStatusCodePages matters more than it looks. Without it, a request that hits no route, or is rejected by content negotiation, returns an empty body with just a status code. With it, those get a ProblemDetails body too, so there is genuinely no path out of the API that returns something unshaped.

The two-pipeline trap

Here is the thing that catches people, and it is worth stating plainly because the documentation does not. ASP.NET Core has two problem-details factories. CustomizeProblemDetails, which you just configured, is invoked by the IProblemDetailsService — that covers minimal-API results, the exception handler, and status-code pages. But MVC controllers build their ProblemDetails through a separate ProblemDetailsFactory, and it does not call CustomizeProblemDetails. So the automatic 400 you get when model binding fails will not carry your traceId, even though you configured it globally.

The automatic model-binding 400 is generated by MVC before your code runs, so the fix is to override the factory it uses and add the same fields there:

using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;

builder.Services
    .AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.InvalidModelStateResponseFactory = context =>
        {
            var problem = new ValidationProblemDetails(context.ModelState)
            {
                Status = StatusCodes.Status400BadRequest,
                Title = "One or more validation errors occurred.",
                Instance = $"{context.HttpContext.Request.Method} " +
                           $"{context.HttpContext.Request.Path}"
            };
            problem.Extensions["traceId"] =
                Activity.Current?.Id ?? context.HttpContext.TraceIdentifier;

            return new BadRequestObjectResult(problem)
            {
                ContentTypes = { "application/problem+json" }
            };
        };
    });

Now the malformed-JSON and wrong-type 400s match everything else. Declaring this shape once in code is also why it pays to declare it in your contract: if you are designing spec-first, the error body belongs in the OpenAPI 3.1 specification next to the success responses, so consumers generate against it.

FluentValidation without the deprecated glue

The old FluentValidation.AspNetCore auto-validation package is deprecated; the maintainers now recommend running validators explicitly rather than hooking the MVC pipeline. That is fine, because explicit validation gives you a cleaner route to a single error shape: validate, and on failure throw. Register the validators once —

using FluentValidation;

builder.Services.AddValidatorsFromAssemblyContaining<Program>();

— then call the validator in the action and throw its result. ValidateAndThrowAsync raises a ValidationException carrying the per-field failures, which the global handler in the next section turns into a proper ValidationProblemDetails. The controller stays thin:

[ApiController]
[Route("orders")]
public sealed class OrdersController : ControllerBase
{
    [HttpPost]
    public async Task<ActionResult> Create(
        CreateOrderRequest request,
        IValidator<CreateOrderRequest> validator,
        CancellationToken ct)
    {
        await validator.ValidateAndThrowAsync(request, ct);

        // ... business logic; if the order id is unknown downstream,
        // throw NotFoundException and let the handler shape the 404.
        return CreatedAtAction(nameof(Create), new { id = 42 });
    }
}

If you prefer not to throw on validation, inject the validator the same way and return ValidationProblem(new ValidationProblemDetails(result.ToDictionary())) instead — ToDictionary() on the FluentValidation result gives you exactly the field-keyed shape the type expects. Both routes end in the same body; throwing simply centralises it.

One handler for everything else

IExceptionHandler, introduced in .NET 8, is where the domain exceptions get mapped. Because it writes through the IProblemDetailsService, your CustomizeProblemDetails enrichment applies automatically — the trace identifier is added for free. Map your known exception types to status codes, special-case validation so the field errors survive, and let anything unrecognised fall through to a 500 that leaks nothing:

using FluentValidation;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

public sealed class GlobalExceptionHandler(
    IProblemDetailsService problemDetailsService,
    ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken)
    {
        logger.LogError(exception, "Unhandled request failure");

        // Validation: preserve the per-field errors.
        if (exception is ValidationException validation)
        {
            var errors = validation.Errors
                .GroupBy(e => e.PropertyName)
                .ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray());

            httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            return await problemDetailsService.TryWriteAsync(new ProblemDetailsContext
            {
                HttpContext = httpContext,
                Exception = exception,
                ProblemDetails = new ValidationProblemDetails(errors)
                {
                    Status = StatusCodes.Status400BadRequest,
                    Title = "One or more validation errors occurred."
                }
            });
        }

        var (status, title) = exception switch
        {
            NotFoundException            => (StatusCodes.Status404NotFound,   "Resource not found"),
            DomainRuleException          => (StatusCodes.Status409Conflict,   "Request conflicts with current state"),
            UnauthorizedAccessException  => (StatusCodes.Status403Forbidden,  "Access denied"),
            _                            => (StatusCodes.Status500InternalServerError, "An unexpected error occurred")
        };

        httpContext.Response.StatusCode = status;
        return await problemDetailsService.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = httpContext,
            Exception = exception,
            ProblemDetails =
            {
                Status = status,
                Title  = title,
                // Never echo an internal message on a 500.
                Detail = status < 500 ? exception.Message : null,
                Type   = $"https://httpstatuses.io/{status}"
            }
        });
    }
}

Returning true tells the framework the exception is handled; returning false would let it fall through to the next handler or the default page. The UseExceptionHandler() call with no arguments works precisely because an IExceptionHandler is registered — that is the .NET 8+ behaviour, and it is why you do not need a fallback error route.

What the client actually sees

With all four pieces in place, every failure a consumer can provoke — a malformed body, a failed business rule, an unknown identifier, an unhandled null — comes back as application/problem+json with the same members and a traceId they can quote in a support ticket. The consistency is not cosmetic. It is what lets a client library deserialise one type, and what lets the internal, service-to-service calls that never touch a browser — the ones you might be securing with mutual TLS between services — surface faults in a form the calling service can act on programmatically rather than log and shrug at.

The trap to remember is the two pipelines. If a single endpoint in your service returns an error that does not match the rest, it is almost always because it went through the factory you did not customise. Test for it: write one integration test that provokes a model-binding 400, a thrown domain exception, and a route miss, and assert all three carry the same content type and the same extension members. If that test passes, you have one error shape. If it does not, you have two, and a client somewhere is about to find out which.

Build and rescue work

Hands-on delivery of this kind is handled by Sixteen Pillars Studio.

Free interactive tool

Website compliance checklist

What your site has to do, based on what it actually does

Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.

Most technology problems are not technology problems. They are control problems.

The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.