Register and activate problem-details middleware
To handle exceptions and return standardized error responses in an ASP.NET Core application, you must register the required services and add the middleware to the request pipeline.
The following example demonstrates how to initialize the Middleware library by calling AddProblemDetails on the service collection and UseProblemDetails on the application builder.
using System;
using Hellang.Middleware.ProblemDetails;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(Array.Empty<string>());
// Register the required services for ProblemDetailsMiddleware using default options.
builder.Services.AddProblemDetails();
var app = builder.Build();
// Add the ProblemDetailsMiddleware to the application pipeline.
// This method returns the same IApplicationBuilder instance for chaining.
var appBuilder = app.UseProblemDetails();
// Verify that UseProblemDetails returns the same application builder instance.
if (!object.ReferenceEquals(app, appBuilder))
{
throw new InvalidOperationException("UseProblemDetails should return the same application builder instance.");
}
Service Registration
The AddProblemDetails extension method on IServiceCollection registers internal services, including the ProblemDetailsFactory and ProblemDetailsOptionsSetup. These services are required for the middleware to resolve and format error details correctly.
Middleware Activation
The UseProblemDetails extension method on IApplicationBuilder inserts the ProblemDetailsMiddleware into the pipeline. This method performs a check to ensure AddProblemDetails was called during service configuration; if the required marker service is missing, it throws an InvalidOperationException.