Xpandables.AspNetCore.Mvc 11.0.0

dotnet add package Xpandables.AspNetCore.Mvc --version 11.0.0
                    
NuGet\Install-Package Xpandables.AspNetCore.Mvc -Version 11.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Xpandables.AspNetCore.Mvc" Version="11.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Xpandables.AspNetCore.Mvc" Version="11.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Xpandables.AspNetCore.Mvc" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Xpandables.AspNetCore.Mvc --version 11.0.0
                    
#r "nuget: Xpandables.AspNetCore.Mvc, 11.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Xpandables.AspNetCore.Mvc@11.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Xpandables.AspNetCore.Mvc&version=11.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Xpandables.AspNetCore.Mvc&version=11.0.0
                    
Install as a Cake Tool

Xpandables.AspNetCore.Mvc

ASP.NET Core MVC integration of the Xpandables results: controller actions return a Result, and every failure — a returned failure or an invalid model — is answered with the same problem details as the minimal API path of Xpandables.AspNetCore.Net, which this package builds on.

Not Native AOT compatible: ASP.NET Core MVC is not supported with Native AOT. Minimal APIs with Xpandables.AspNetCore.Net are.

dotnet add package Xpandables.AspNetCore.Mvc
builder.Services.AddControllers();
builder.Services.AddXControllerResultMvcOptions();
[ApiController]
[Route("api/orders")]
public sealed class OrdersController(IOrderService orders) : ControllerBase
{
    [HttpGet("{id}")]
    public async Task<IActionResult> Get(Guid id, CancellationToken ct) =>
        (await orders.GetAsync(id, ct)).ToActionResult();   // Result<Order>: 200 with the order, or problem details

    [HttpPost]   // an invalid CreateOrder is answered by [ApiController] with the same problem details
    public IActionResult Create(CreateOrder request) =>
        Result.Created(orders.Create(request)).ToActionResult();
}

On a controller without [ApiController], apply [ControllerResultValidationFilter] to answer an invalid model the same way.

Type Namespace Role
ControllerResultMvcOptions Microsoft.AspNetCore.Mvc Adds ControllerResultFilter to MvcOptions, and makes [ApiController]'s invalid-model response (ApiBehaviorOptions.InvalidModelStateResponseFactory) a Result. Endpoint routing and content negotiation stay the application's.
ControllerResultFilter Microsoft.AspNetCore.Mvc.Filters Writes a Result returned by an action: a failure as problem details with its status, a success with a value as its value, a success without a value as its status alone.
ControllerResultValidationFilterAttribute Microsoft.AspNetCore.Mvc.Filters Turns an invalid model state into a 400 failure result before the action runs. Not registered globally: apply [ControllerResultValidationFilter] to the controllers or actions that should answer that way (a view controller re-renders its form instead).
ControllerResultServiceCollectionExtensions Microsoft.Extensions.DependencyInjection AddXControllerResultMvcOptions(): registers ControllerResultMvcOptions; calling it again adds nothing more.
MvcResultExtensions Microsoft.AspNetCore.Http ModelStateDictionary.ToResult(), Result.ToModelStateDictionary(), Result.ToActionResult(), HttpContext.GetMvcJsonSerializerOptions().

Registration

AddXControllerResultMvcOptions() calls AddMvcCore() first, so MVC's own options setup runs before this one whether AddControllers() is called before or after it. It registers ControllerResultMvcOptions once (TryAddEnumerable) as both IConfigureOptions<MvcOptions> and IConfigureOptions<ApiBehaviorOptions>:

  • ControllerResultFilter is added as a global filter with order int.MinValue. It is an IAsyncAlwaysRunResultFilter: it runs even when another filter short-circuits the action.
  • InvalidModelStateResponseFactory answers an invalid model with a BadRequestObjectResult of the model state as a result, which the filter writes as problem details.

Controller Result Filter

The filter acts on an ObjectResult whose value is a Result (what ToActionResult(), Ok(result) and the like return), and leaves any other action result alone:

  1. the registered IResultHeaderWriter (or the default ResultHeaderWriter when none is registered) writes the status, the content type of a response with a body (when none is set), the Location of a 201 or a redirect and the result's headers — nothing is written once the response has started;
  2. a failure (4xx, 5xx) first drops what the action set on the response (headers, status, buffered body), then becomes an ObjectResult with the problem details and the result's status; a 499 on a request that was not aborted is a 500;
  3. a success with a value, whose status carries a body (a 2xx other than 204), writes that value with the result's status (Ok(Result.Created(order)) answers 201);
  4. any other result — a success without a value, a 204, a redirect, a 304 — becomes a StatusCodeResult with the result's status (no body).

The Result envelope itself is never serialized.

One error format

Every failure is written by ControllerResultFilter as problem details with its status: a Result an action returns and an invalid model (through [ControllerResultValidationFilter], or [ApiController]'s automatic 400), alike. The problem details are built by Xpandables.AspNetCore.Net's result.ToProblemDetails(httpContext) (title and detail from the result or the status texts, instance the request path, type https://httpstatuses.io/{status}, the result's extensions), then, like the minimal API path, carry a traceId (Activity.Current.Id, else HttpContext.TraceIdentifier) and go through ProblemDetailsOptions.CustomizeProblemDetails. A failed Result is logged as on the minimal API path, in the ResultMiddleware category: a 4xx at Information with its error keys, a 5xx at Error with its exception.

A 4xx failure carrying errors (in development, also a 4xx carrying an exception, under exception) is MVC's ValidationProblemDetails (any other failure plain ProblemDetails), which MVC's JSON and XML formatters both write, whose errors are keyed by member, by JSON path for a body that failed to deserialize ($.items[0].id), and $ for the model level (ValidationResultExtensions.ObjectLevelKey, the key of every Xpandables object-level failure).

ControllerBase.ValidationProblem(), ValidationProblem(modelState) and ValidationProblem(detail: …) do not go through InvalidModelStateResponseFactory (the parameterless one calls ValidationProblem(ModelState)): they return MVC's own ValidationProblemDetails, built by the registered ProblemDetailsFactory, with model-level errors under the empty key. BadRequest(ModelState) returns MVC's SerializableError. ControllerResultFilter leaves both alone. For the library's format from inside an action, return ModelState.ToResult().ToActionResult().

To keep MVC's own [ApiController] response, set the factory after AddXControllerResultMvcOptions():

builder.Services.Configure<ApiBehaviorOptions>(options => options.InvalidModelStateResponseFactory = context =>
    new BadRequestObjectResult(context.HttpContext.RequestServices.GetRequiredService<ProblemDetailsFactory>()
        .CreateValidationProblemDetails(context.HttpContext, context.ModelState))
    {
        ContentTypes = { "application/problem+json", "application/problem+xml" }
    });

Model State and Results

Result failure = ModelState.ToResult();                              // 400
Result withParserMessages = ModelState.ToResult(isDevelopment: true); // keeps the input formatters' messages
Result notFound = ModelState.ToResult(HttpStatusCode.NotFound);      // another status
ModelStateDictionary state = result.ToModelStateDictionary();        // for a view
ModelStateDictionary withException = result.ToModelStateDictionary(isDevelopment: true);
  • ModelState.ToResult(statusCode = 400, isDevelopment = false) returns a failed result with one error entry per key that has errors, in the model state's order. MVC's model level (the empty key) and System.Text.Json's root ($) both go under $; a JSON path stays as it is. An error without a message — a binding exception — or with a blank one gets MVC's own text, "The input was not valid." (never the exception's message). Outside development (isDevelopment: false, the default; [ApiController]'s factory and [ControllerResultValidationFilter] read the request's environment), an error under a System.Text.Json path key ($, $.name, $[0]) — an input formatter's, whose message is the parser's (CLR types, positions) — gets the status detail as message, as the minimal API path answers a binding failure; an error under any other key ($top) keeps its message.
  • Result.ToModelStateDictionary(isDevelopment = false) copies the result's non-blank error messages under their keys, and puts $ back under the empty key, where a view's validation summary shows model-level errors. With isDevelopment: true, the result's exception is added under exception.
  • Result.ToActionResult() returns an ObjectResult carrying the result, with the result's status: ControllerResultFilter turns it into the response, so register AddXControllerResultMvcOptions(); without the filter, the Result itself is serialized.
  • The error keys of an exception answered by ResultMiddleware follow Microsoft.AspNetCore.Http.Json.JsonOptions (the minimal API options), so an MVC host that changes its naming policy (AddJsonOptions) configures Microsoft.AspNetCore.Http.Json.JsonOptions the same way.
  • HttpContext.GetMvcJsonSerializerOptions() returns the JsonSerializerOptions of MVC's JsonOptions (AddJsonOptions), as opposed to the minimal API options returned by GetJsonSerializerOptions().
Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
11.0.0 0 11/29/2026