Skip to main content

Register and activate problem-details middleware

To integrate ProblemDetails into an ASP.NET Core application, you must register the required services and then add the middleware to the request processing pipeline.

The following example demonstrates how to initialize the Middleware library using AddProblemDetails and 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 using the parameterless overload.
// This must be called before UseProblemDetails.
builder.Services.AddProblemDetails();

var app = builder.Build();

// Add the ProblemDetailsMiddleware to the application pipeline.
// UseProblemDetails returns the same IApplicationBuilder instance for chaining.
var result = app.UseProblemDetails();

if (!object.ReferenceEquals(app, result))
{
throw new InvalidOperationException("UseProblemDetails must return the same IApplicationBuilder instance.");
}

Registration and Activation

The AddProblemDetails extension method on IServiceCollection registers internal services, such as the ProblemDetailsFactory and a marker service used for validation. If you attempt to call UseProblemDetails without first calling AddProblemDetails, the middleware throws an InvalidOperationException to ensure the pipeline is correctly configured.

The UseProblemDetails extension method on IApplicationBuilder inserts the ProblemDetailsMiddleware into the pipeline. It is typically placed early in the middleware chain to catch exceptions from subsequent components and convert them into RFC 7807 problem details responses.