Problem Details standardizes machine-readable error responses for HTTP APIs. It gives clients a consistent JSON structure instead of requiring a different error format for every endpoint. section 5.3.2
Minimal APIs provide Results.Problem() for general errors and Results.ValidationProblem() for validation errors. Problem() defaults to status 500, while ValidationProblem() defaults to 400 and accepts a dictionary of validation messages. section 5.3.2
Consistent Problem Details responses can cover errors generated in several places:
- Endpoint handlers can return Problem Details directly for conditions such as a missing resource or duplicate identifier. section 5.3.2
- ExceptionHandlerMiddleware can convert unhandled exceptions automatically when AddProblemDetails() registers the IProblemDetailsService. section 5.3.3
- StatusCodePagesMiddleware can add a Problem Details body to error responses that otherwise have no response body. section 5.3.3
Duplicate fruit identifier
A POST request that reuses a fruit identifier returns ValidationProblem() with an id error such as “A fruit with this id already exists.” The client receives validation information in the standard JSON format. section 5.3.2
Listing 5.5 Returning Problem Details using Results.Problem
using System.Collections.Concurrent;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
var _fruit = new ConcurrentDictionary<string, Fruit>();
app.MapGet("/fruit", () => _fruit);
app.MapGet("/fruit/{id}", (string id) =>
_fruit.TryGetValue(id, out var fruit)
? TypedResults.Ok(fruit)
: Results.Problem(statusCode: 404)); #1
app.MapPost("/fruit/{id}", (string id, Fruit fruit) =>
_fruit.TryAdd(id, fruit)
? TypedResults.Created($"/fruit/{id}", fruit)
: Results.ValidationProblem(new Dictionary<string, string[]> #2
{ #2
{"id", new[] {"A fruit with this id already exists"}} #2
})); #2
#1 Returns a Problem Details object with a 404 status code
#2 Returns a Problem Details object with a 400 status code and includes the validation errors
Inspect the minimal API example that returns a 404 Problem Details response and a validation response for duplicate fruit identifiers. section 5.3.2

