Register and activate problem-details middleware
To integrate Middleware into an ASP.NET Core application, you must register the required services and then activate the middleware in the request pipeline. This is achieved using the AddProblemDetails and UseProblemDetails extension methods.
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 marker services to the container.
builder.Services.AddProblemDetails();
var app = builder.Build();
// Add the ProblemDetailsMiddleware to the request pipeline.
// This method returns the same IApplicationBuilder instance for chaining.
var result = app.UseProblemDetails();
// Verify that the middleware registration returns the original application builder.
if (!object.ReferenceEquals(app, result))
{
throw new InvalidOperationException("UseProblemDetails must return the same IApplicationBuilder instance.");
}
The AddProblemDetails method prepares the dependency injection container by adding internal services like ProblemDetailsMarkerService, which the middleware uses to verify that registration has occurred. If UseProblemDetails is called without a prior call to AddProblemDetails, the application will throw an InvalidOperationException at startup.