AddProblemDetails registers IProblemDetailsService in dependency injection and enables ASP.NET Core middleware to generate Problem Details responses automatically. section 5.3.3
Register Problem Details for exceptions
Add the service before building the application, then configure exception handling without an error path. When an endpoint throws, the middleware uses IProblemDetailsService to create the response. AddStatusCodePages can similarly add a Problem Details body to an otherwise empty 404 response. section 5.3.3
Listing 5.6 Configuring ExceptionHandlerMiddleware to use Problem Details
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services.AddProblemDetails(); #1 WebApplication app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler(); #2 } app.MapGet("/", void () => throw new Exception()); #3 app.Run(); #1 Adds the IProblemDetailsService implementation #2 Configures the ExceptionHandlerMiddleware without a path so that it uses the IProblemDetailsService #3 Throws an exception to demonstrate the behavior
Shows AddProblemDetails alongside UseExceptionHandler and a throwing endpoint, with annotations identifying each configuration step. section 5.3.3
