Skip to main content

Add problem-details MVC conventions

When you build an ASP.NET Core API, MVC's default behavior for handling validation errors or specific status codes might not align with the custom formatting provided by the Middleware Problem Details package. To ensure that MVC components—such as ApiBehaviorOptions and the application model—respect the middleware's configuration, you must register the library's MVC conventions.

The AddProblemDetailsConventions extension method, found in the Hellang.Middleware.ProblemDetails.Mvc namespace, bridges the gap between standard MVC error handling and the middleware. By calling this method on your IServiceCollection, you replace the default MvcProblemDetailsFactory with the middleware's implementation and register internal providers like ProblemDetailsApplicationModelProvider. This ensures that status code results and validation errors are consistently transformed into the ProblemDetails format defined in your middleware setup.

The method follows the standard ASP.NET Core builder pattern, returning the same IServiceCollection instance to allow for fluent configuration.

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 Problem Details.
// This method registers the ProblemDetailsApplicationModelProvider and
// configures ApiBehaviorOptions to use the middleware's factory.
var returnedServices = services.AddProblemDetailsConventions();

// The public contract of AddProblemDetailsConventions requires that it
// returns the original IServiceCollection instance to support method chaining.
if (!object.ReferenceEquals(services, returnedServices))
{
throw new InvalidOperationException("The IServiceCollection extension method did not return the expected collection instance.");
}

Registration Contract

When you invoke AddProblemDetailsConventions on an IServiceCollection, Middleware establishes several key integrations:

  • Factory Replacement: It replaces the singleton registration of MvcProblemDetailsFactory with a version that resolves the middleware's own ProblemDetailsFactory. This ensures that even when MVC internally generates a problem response, it uses your custom mapping logic.
  • Application Model Setup: It adds ProblemDetailsApplicationModelProvider to the collection of IApplicationModelProvider services. This provider is responsible for injecting the ProblemDetailsResultFilter into the MVC pipeline.
  • API Behavior Configuration: It registers a configuration action for ApiBehaviorOptions via ProblemDetailsApiBehaviorOptionsSetup, which coordinates how the framework handles automatic 400 Bad Request responses.

This registration is typically performed in the ConfigureServices method of your Startup class or in your Program.cs file alongside other MVC service registrations.