liveBook · Manning

AddProblemDetails

As explained in ASP.NET Core in Action, 3e

AddProblemDetails is an ASP.NET Core service-registration extension method that registers IProblemDetailsService and configures Problem Details generation.

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Defines registration and middleware prerequisites but does not detail customization of generated Problem Details.
Examples
Demonstrates Program.cs registration with exception handling, a throwing endpoint, and status-code pages for a 404 response.
What it assumes
Assumes a WebApplicationBuilder and middleware pipeline, while teaching the required service registration.
What you can do after
Operate/configure it: register the service and enable middleware to return Problem Details for exceptions and empty error responses.
How it connects
Connects dependency injection with ExceptionHandlerMiddleware, DeveloperExceptionPageMiddleware, StatusCodePagesMiddleware, and Problem Details.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.