Add problem-details MVC conventions
Integrating Middleware with ASP.NET Core MVC requires aligning the framework's built-in error handling with the library's custom logic. When you use standard MVC controllers, the framework often applies its own ClientErrorMapping or uses a default ProblemDetailsFactory, which can lead to inconsistent error responses that bypass your Middleware configuration.
The AddProblemDetailsConventions extension method in the Hellang.Middleware.ProblemDetails.Mvc namespace resolves this by registering specific MVC conventions and service overrides. Specifically, it replaces the default MvcProblemDetailsFactory with one that delegates to the library's ProblemDetailsFactory, ensuring that even errors generated by MVC (such as validation failures) follow your configured rules.
The method is designed as a fluent API on IServiceCollection. It returns the same collection instance passed into it, allowing you to chain it with other service registrations.
using System;
using Hellang.Middleware.ProblemDetails.Mvc;
using Microsoft.Extensions.DependencyInjection;
// Initialize a new service collection for the application.
var services = new ServiceCollection();
// Register the MVC conventions for Middleware.
// This method configures MVC to use the library's ProblemDetails logic
// and returns the original IServiceCollection instance.
var result = services.AddProblemDetailsConventions();
// Verify that the method adheres to the fluent API contract by returning the same instance.
if (!object.ReferenceEquals(services, result))
{
throw new InvalidOperationException("AddProblemDetailsConventions must return the same IServiceCollection instance to support fluent chaining.");
}
By calling this method on the IServiceCollection, Middleware establishes a public registration contract where:
- The MVC
ClientErrorMappingis disabled to prevent the framework from overriding custom problem details. - A custom result filter is registered to handle
ObjectResultinstances containing strings. - The internal MVC
ProblemDetailsFactoryis redirected to the Middleware implementation.
This ensures that the error response format remains consistent across your entire application, whether the error is thrown manually, generated by a filter, or produced by MVC's automatic validation.