Add problem-details MVC conventions
When building APIs with ASP.NET Core MVC, the framework provides built-in mechanisms for handling client errors, such as ClientErrorMapping. However, these defaults may conflict with or duplicate the behavior of the Middleware library. The AddProblemDetailsConventions extension method ensures that MVC's internal behavior is aligned with the library's problem details generation.
Registration Contract
The AddProblemDetailsConventions method is an extension of IServiceCollection defined in the Hellang.Middleware.ProblemDetails.Mvc namespace. Its primary role is to register a set of conventions and services that integrate the library with the MVC pipeline.
When you call this method, it performs the following registrations:
- Replaces the default
MvcProblemDetailsFactorywith a version that delegates to the library'sProblemDetailsFactory. - Disables MVC's built-in
ClientErrorMappingto prevent redundant error responses. - Adds an
IApplicationModelProvider(ProblemDetailsApplicationModelProvider) to automatically apply error response types to controllers decorated with[ApiController]. - Registers a result filter (
ProblemDetailsResultFilter) that interceptsObjectResultresponses containing strings and converts them into formalProblemDetailsobjects.
The method follows the standard IServiceCollection pattern, returning the same instance it was called on to support fluent configuration.
using System;
using Hellang.Middleware.ProblemDetails.Mvc;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
// Register the MVC conventions for ProblemDetails
var result = services.AddProblemDetailsConventions();
// The method must return the original ServiceCollection instance to support chaining
if (!object.ReferenceEquals(services, result))
{
throw new InvalidOperationException("AddProblemDetailsConventions did not return the original IServiceCollection instance.");
}