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
<PackageReference Include="Xpandables.AspNetCore.Mvc" Version="11.0.0" />
<PackageVersion Include="Xpandables.AspNetCore.Mvc" Version="11.0.0" />
<PackageReference Include="Xpandables.AspNetCore.Mvc" />
paket add Xpandables.AspNetCore.Mvc --version 11.0.0
#r "nuget: Xpandables.AspNetCore.Mvc, 11.0.0"
#:package Xpandables.AspNetCore.Mvc@11.0.0
#addin nuget:?package=Xpandables.AspNetCore.Mvc&version=11.0.0
#tool nuget:?package=Xpandables.AspNetCore.Mvc&version=11.0.0
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>:
ControllerResultFilteris added as a global filter with orderint.MinValue. It is anIAsyncAlwaysRunResultFilter: it runs even when another filter short-circuits the action.InvalidModelStateResponseFactoryanswers an invalid model with aBadRequestObjectResultof 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:
- the registered
IResultHeaderWriter(or the defaultResultHeaderWriterwhen none is registered) writes the status, the content type of a response with a body (when none is set), theLocationof a 201 or a redirect and the result's headers — nothing is written once the response has started; - a failure (4xx, 5xx) first drops what the action set on the response (headers, status, buffered body), then
becomes an
ObjectResultwith the problem details and the result's status; a 499 on a request that was not aborted is a 500; - 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); - any other result — a success without a value, a 204, a redirect, a 304 — becomes a
StatusCodeResultwith 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. WithisDevelopment: true, the result's exception is added underexception.Result.ToActionResult()returns anObjectResultcarrying the result, with the result's status:ControllerResultFilterturns it into the response, so registerAddXControllerResultMvcOptions(); without the filter, theResultitself is serialized.- The error keys of an exception answered by
ResultMiddlewarefollowMicrosoft.AspNetCore.Http.Json.JsonOptions(the minimal API options), so an MVC host that changes its naming policy (AddJsonOptions) configuresMicrosoft.AspNetCore.Http.Json.JsonOptionsthe same way. HttpContext.GetMvcJsonSerializerOptions()returns theJsonSerializerOptionsof MVC'sJsonOptions(AddJsonOptions), as opposed to the minimal API options returned byGetJsonSerializerOptions().
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Xpandables.AspNetCore.Net (>= 11.0.0)
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 |