Register and activate problem-details middleware
To integrate Middleware into an ASP.NET Core application, you must register its services in the dependency injection container and then activate the middleware in the request pipeline.
The following example demonstrates a complete top-level program that initializes the application builder, registers the required services using AddProblemDetails, builds the application, and activates the middleware using UseProblemDetails.
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 ProblemDetails middleware.
// This adds the ProblemDetailsFactory and internal marker services.
builder.Services.AddProblemDetails();
var app = builder.Build();
// Add the ProblemDetailsMiddleware to the application pipeline.
// This must be called after AddProblemDetails has been called on the service collection.
var appBuilder = app.UseProblemDetails();
// Verify that UseProblemDetails returns the same IApplicationBuilder instance for chaining.
if (!object.ReferenceEquals(app, appBuilder))
{
throw new InvalidOperationException("UseProblemDetails should return the same application builder instance.");
}
Service Registration
The AddProblemDetails extension method on IServiceCollection is responsible for registering the ProblemDetailsFactory and a internal marker service (ProblemDetailsMarkerService). These services are required for the middleware to resolve options and generate compliant error responses.
Middleware Activation
The UseProblemDetails extension method on IApplicationBuilder inserts the ProblemDetailsMiddleware into the request pipeline. During activation, it checks for the presence of the marker service registered by AddProblemDetails. If the services have not been registered, UseProblemDetails throws an InvalidOperationException to prevent runtime failures during request processing.