Add problem-details MVC conventions
When building APIs with ASP.NET Core MVC, the framework provides built-in mechanisms for handling client errors and generating responses. To ensure these built-in behaviors align with the custom error handling logic provided by Middleware, you use the AddProblemDetailsConventions extension method. This method synchronizes MVC's internal factories and filters with the Middleware's configuration, preventing inconsistent error formats between standard MVC validation errors and custom exceptions.
Integrating MVC Conventions
You register these conventions during service configuration. The AddProblemDetailsConventions method is available as an extension on IServiceCollection within the Hellang.Middleware.ProblemDetails.Mvc namespace. By calling this method, you instruct Middleware to take control of how MVC produces ProblemDetails objects.
Internally, the AddProblemDetailsConventions method performs several key registrations in the IServiceCollection:
- Factory Synchronization: It replaces the default
MvcProblemDetailsFactorywith a singleton that resolves the Middleware's ownProblemDetailsFactory. This ensures that whether a response is generated by an MVC controller or the middleware, the same factory logic is applied. - API Behavior Configuration: It adds a transient configuration for
ApiBehaviorOptionsviaProblemDetailsApiBehaviorOptionsSetup. This is typically used to disable the default MVC client error mapping, allowing the middleware to handle those scenarios instead. - Application Model Extension: It registers a
ProblemDetailsApplicationModelProviderto modify the MVC application model, ensuring that the necessary metadata for problem details is available to the framework. - Result Filtering: It registers a
ProblemDetailsResultFilterFactoryas anIMvcFilterMetadata. This filter intercepts results to ensure that responses, such as those returning string values or specific object results, are correctly transformed intoProblemDetailsformat when appropriate.
The following example demonstrates the registration contract. It initializes a service collection, applies the conventions, and verifies that the method adheres to the fluent interface pattern by returning the original collection instance.
using System;
using Hellang.Middleware.ProblemDetails.Mvc;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
// Register the MVC conventions for Problem Details.
// This method returns the IServiceCollection to support method chaining.
var returnedServices = services.AddProblemDetailsConventions();
// Verify the registration contract: the method must return the same ServiceCollection instance.
if (!object.ReferenceEquals(services, returnedServices))
{
throw new InvalidOperationException("AddProblemDetailsConventions did not return the original IServiceCollection.");
}