Xpandables.AspNetCore.Net
11.0.0
dotnet add package Xpandables.AspNetCore.Net --version 11.0.0
NuGet\Install-Package Xpandables.AspNetCore.Net -Version 11.0.0
<PackageReference Include="Xpandables.AspNetCore.Net" Version="11.0.0" />
<PackageVersion Include="Xpandables.AspNetCore.Net" Version="11.0.0" />
<PackageReference Include="Xpandables.AspNetCore.Net" />
paket add Xpandables.AspNetCore.Net --version 11.0.0
#r "nuget: Xpandables.AspNetCore.Net, 11.0.0"
#:package Xpandables.AspNetCore.Net@11.0.0
#addin nuget:?package=Xpandables.AspNetCore.Net&version=11.0.0
#tool nuget:?package=Xpandables.AspNetCore.Net&version=11.0.0
π¦ AspNetCore.Net
ASP.NET Core integration layer β middleware, filters, pipeline behaviors, routing abstractions, and DI extensions for the Xpandables ecosystem
Getting Started β’ Native AOT β’ Result Middleware β’ Endpoint Validation β’ Minimal API Routing β’ Event Context Middleware β’ Pipeline Behaviors β’ IUseService β’ DI Methods
π Overview
Xpandables.AspNetCore.Net bridges the Xpandables ecosystem (Result pattern, event sourcing, handlers) into ASP.NET Core minimal APIs:
ResultMiddlewareturns unhandled exceptions into problem details, andResultEndpointFilterwrites a returnedResultas its value or as problem details;ResultEndpointValidationFiltervalidates theIRequiresValidationarguments of an endpoint before it runs;EventContextMiddlewarepropagates the correlation and causation identifiers of a request;IMinimalEndpointRoutegroups routes in modules, andIUseServiceruns startup hooks;- the validation, unit-of-work and authorization pieces plug into the Xpandables.Handlers pipeline.
The package is Native AOT compatible: its registrations are generated (Xpandables.Generators flows with it) and nothing in it uses reflection. MVC support lives in Xpandables.AspNetCore.Mvc, which is not Native AOT compatible (ASP.NET Core MVC is not).
π Getting Started
dotnet add package Xpandables.AspNetCore.Net
Xpandables.Generators comes with the package: no separate install.
var builder = WebApplication.CreateSlimBuilder(args);
builder.Services
.AddXJsonSerializerOptions(o => o.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default))
.AddXResultMiddleware()
.AddXResultProblemDetails()
.AddXResultEndpointValidator()
.AddXValidator<CreateOrder, CreateOrderValidator>()
.AddXMinimalEndpointRoutesGenerated() // generated: every IMinimalEndpointRoute of the application
.AddXServicesGenerated(); // generated: every IAddService
var app = builder.Build();
app.UseXResultMiddleware();
await app.UseXServicesGeneratedAsync(); // generated: every IUseService, in ascending Order
app.UseXMinimalEndpointRoutes();
await app.RunAsync();
β‘ Native AOT
Registrations are generated.
AddXMinimalEndpointRoutesGenerated(),AddXServicesGenerated(),UseXServicesGenerated()/UseXServicesGeneratedAsync()andAddX{Assembly}Handlers()are emitted in your application by Xpandables.Generators; nothing is discovered by scanning assemblies.JSON metadata.
AddXJsonSerializerOptionsadds the library's own source-generated metadata (ElementCollectionContext,ElementEntryContext) to the HTTP JSON options, then applies your configuration, and registers those options asJsonSerializerOptionsand as anIJsonSerializerContext(TryAdd). Add your own context for your payloads, including everyResultandResult<T>an endpoint returns: a result is never written (the result filter writes its value or its problem details), but the Request Delegate Generator asks for the metadata of the declared return type when it builds the endpoint.[JsonSerializable(typeof(CreateOrder))] [JsonSerializable(typeof(Order))] [JsonSerializable(typeof(Result<Order>))] internal sealed partial class AppJsonContext : JsonSerializerContext;System.Text.Json reads
DateOnlyandTimeOnlynatively: no converter to add.Validators are registered explicitly with
AddXValidator<TArgument, TValidator>()(Xpandables.Validations), or by the generatedAddX{Assembly}Validators().Handlers are statically resolvable. The Request Delegate Generator analyses each
Map*call where it is written, including inside anIMinimalEndpointRoute. Pass a lambda or a method group directly toMap*: a delegate held in a variable or returned from a factory producesRDG002and falls back to the reflection-basedRequestDelegateFactory, which does not survive ahead-of-time compilation.One open-generic registration remains:
AddXLazyResolved()registersLazy<>, closed by the container at run time; under Native AOT it works for reference types only (Lazy<int>fails). Every other registration is closed.Calling a registration twice registers once:
AddXLazyResolved(),AddXResultMiddleware()andAddXEventContextMiddleware<T>()keep an earlier registration, and the behaviors are added once, also after a decoration.
β Result Middleware
builder.Services.AddXResultMiddleware(); // ResultMiddleware, singleton
builder.Services.AddXResultProblemDetails(); // optional: the result-aware IProblemDetailsService
app.UseXResultMiddleware(); // throws InvalidOperationException when AddXResultMiddleware() was not called
app.MapPost("/api/orders", (CreateOrder request) =>
{
Order order = new(Guid.CreateVersion7(), request.Name);
Result<Order> created = Result.Created(order);
created.WithLocation(new Uri($"/api/orders/{order.Id}", UriKind.Relative)); // sets the Location of the same instance
return created;
})
.WithXResultSupport();
How a failure is written
A failure is written the same way from the middleware, the endpoint filter and the endpoint validator:
- the registered
IResultHeaderWriter(or, when none is registered, the defaultResultHeaderWriter) writes the status and the result's headers; once the response has started, nothing more is written; IProblemDetailsService.TryWriteAsyncwrites the problem details built byresult.ToProblemDetails(httpContext)(see Result to Problem Details);- when no problem details service is registered, or none of its writers accepts the request (a client that accepts
only
text/html),TypedResults.Problemwrites them asapplication/problem+json.
Exceptions
ResultMiddleware catches the exceptions of the rest of the pipeline and answers with problem details, as long as the
response has not started (an exception thrown after that goes back to the host). The exception is logged first. The
registered IExceptionStatusMapper (System.Net) is consulted first, for every exception, and the status it gives wins
(services.AddSingleton<IExceptionStatusMapper, MyMapper>();).
Before an error is written, the response is cleared when it has not started: headers the endpoint set, its status
and its buffered body are dropped, together with any header an earlier middleware wrote directly. Headers added again
when the response starts (Response.OnStarting, as the correlation header and the CORS headers of ASP.NET Core are)
survive.
| Exception | Answer |
|---|---|
OperationCanceledException or IOException while HttpContext.RequestAborted is signalled |
none: the client is gone, the exception goes back to the host |
TargetInvocationException |
its inner exception is answered |
ResultException |
the result it carries |
BadHttpRequestException |
its status; the error keyed by the parameter name ("int id" β id) |
ValidationException / MultipleValidationException |
400 with the member errors |
AuthenticationException |
401 |
UnauthorizedAccessException, SecurityException |
403 |
DBConcurrencyException, EventStreamConcurrencyException (a lost append race) |
409 |
TimeoutException |
504 |
HttpRequestException (an upstream call failed) |
502; 504 when it carries 408/504 or wraps a TimeoutException |
OperationCanceledException wrapping a TimeoutException |
504 |
any other OperationCanceledException (an application token) |
500 |
anything else (ArgumentException, KeyNotFoundException, NotSupportedException...) |
500, without the exception's message outside development |
The title and detail come from the registered status texts (IHttpStatusCodeExtension, or the default ones), for a
ValidationException too, whether the endpoint throws it or the validation filter reports it; a ResultException keeps
its result as it is, the status texts filling the title and detail it does not set. The exception message reaches the problem title β and a BadHttpRequestException's message its parameter error,
or its detail when it names no parameter β only when the host's IWebHostEnvironment.IsDevelopment(); a host without
an IWebHostEnvironment is production.
ResultMiddleware and ResultEndpointFilter work without AddXResultProblemDetails(): the problem details are then
written as JSON.
Result Problem Details Service
AddXResultProblemDetails() calls AddProblemDetails() and replaces IProblemDetailsService with
ResultProblemDetailsService (singleton):
- problem details supplied by the caller are kept as they are (the filter and the middleware supply them from the
result); missing members are filled: status (400 when none), title and detail from the status texts,
instance(the request path, without verb or query string) andtype(https://httpstatuses.io/{status}); - problem details that carry nothing but the exception β ASP.NET Core's
UseExceptionHandlersupplies a bare 500 β are rebuilt from the exception with the mapping above, soUseExceptionHandleranswers with the exception's mapped status too. A status the application chose (ExceptionHandlerOptions.StatusCodeSelector, anIExceptionHandler) and problem details it filled itself are kept; - the response gets the status,
application/problem+jsonunless a content type is already set,Cache-Control: no-cache, no-store, must-revalidateandPragma: no-cache; - the registered
IProblemDetailsWriters are tried in order;TryWriteAsyncreturnsfalsewhen none accepts the request,WriteAsyncthrowsInvalidOperationException.
Result Endpoint Filter
WithXResultSupport() adds ResultEndpointFilter to an endpoint (or a route group):
- a
Resultthat is not a failure is written with its status,Location(a 201 or a 3xx) and headers, then its value when its status carries a body (a 2xx other than 204); a redirect, a 304, a 204 and a result without a value are answered with their status and no body; - a failure is written as above, and the filter returns
Results.Empty; before an error is written, the response is cleared when it has not started: headers the endpoint set, its status and its buffered body are dropped, together with any header an earlier middleware wrote directly; headers added again when the response starts (Response.OnStarting, as the correlation header and the CORS headers of ASP.NET Core are) survive; - a 499 (client closed request) on a request that was not aborted is written as a 500, as the middleware answers it;
- a request whose parameter binding failed β a route, query or header value that does not parse, a missing required
parameter β is written as problem details with the status the framework set (.NET 11 runs the endpoint filters then,
without the handler, when
RouteHandlerOptions.ThrowOnBadRequestisfalse, the default outside development; in development set it tofalseto get the same answer instead of the developer exception page). The validation and idempotency filters pass such a request on without reading its partly bound arguments; - any other return value passes through unchanged.
A content type is set only for a response with a body (a 2xx other than 204, with a value): the one the endpoint
declares for that status (Producesβ¦), else the framework default. A string value is written as text
(text/plain; charset=utf-8, unless a non-JSON type is declared; a declared text/* type without charset gets
charset=utf-8), as minimal APIs write strings.
It also rewrites the response metadata (OpenAPI): a Result<T> endpoint is described as returning T (text/plain
for a string, unless a non-JSON type is declared), a Result endpoint as returning no body. The failure statuses
depend on the endpoint: declare them with Produces400BadRequest(), Produces404NotFound()β¦
Result Header Writer
builder.Services.AddXResultHeaderWriter(); // TryAdd (singleton): keeps one registered earlier
builder.Services.AddXResultHeaderWriter<CustomHeaderWriter>(); // Replace (scoped)
ResultHeaderWriter (stateless) writes:
- the status;
- for a response with a body, the content type described above;
- for a 201 or a redirect (3xx), the
Location: escaped, non-ASCII characters percent-encoded as UTF-8, an absolute URI's host in IDN form; no other status carries one; - the result's headers. A header whose name is not an RFC 9110 token, or whose value holds anything but visible ASCII, space and tab, is dropped: Kestrel rejects it, and a CR/LF would split the response.
It writes no WWW-Authenticate challenge: a 401 from a result carries none, the authentication handler owns the
challenge (Results.Challenge()). Nothing is written once the response has started.
Result to Problem Details
ProblemDetails problem = result.ToProblemDetails(httpContext);
Result failure = badHttpRequestException.ToResult(httpContext);
ToProblemDetails uses the result's title and detail, or the registered status texts; instance is the request path
and type is https://httpstatuses.io/{status}; the result's extensions become the problem's extensions. A 4xx failure carrying errors gives an
HttpValidationProblemDetails whose errors are the result's non-blank messages, keyed as the result keys them ($
for the object level), plus the exception under exception in development (where a 4xx carrying an exception without
errors is validation problem details too); any other failure (a 404 without errors, a 5xx) gives plain ProblemDetails,
without errors. It is the framework's HttpValidationProblemDetails, whose metadata
ASP.NET Core source-generates, so a trimmed or Native AOT application can write it; ToProblemDetails<T> fills another
validation type (MVC's ValidationProblemDetails) directly.
Logging
ResultMiddleware and ResultEndpointFilter log under the ResultMiddleware category:
| Event id | Level | Message |
|---|---|---|
| 1 | Information | a request was answered with a client failure (4xx): method, path, status and the error keys, never their values |
| 2 | Error | a request was answered with a server failure (5xx), with its exception (the filter, the middleware) |
| 3 | Debug | a request completed with a successful result (the filter) |
A 4xx without errors logs an empty key list. An exception the application's IExceptionStatusMapper answers with a
status that is not a failure (a redirect) is not logged.
A failure is logged in a scope carrying the request's CorrelationId (from ICorrelationContextAccessor, set by
EventContextMiddleware); the MVC result filter logs the same way.
π‘οΈ Endpoint Validation
public sealed record CreateOrder(string Name) : IRequiresValidation;
public sealed class CreateOrderValidator : Validator<CreateOrder>
{
public override IReadOnlyCollection<ValidationResult> Validate(CreateOrder instance) =>
string.IsNullOrEmpty(instance.Name) ? [new ValidationResult("Name is required.", ["Name"])] : [];
}
builder.Services.AddXResultEndpointValidator(); // TryAdd: keeps a validator, provider or header writer registered earlier
builder.Services.AddXValidator<CreateOrder, CreateOrderValidator>();
app.MapPost("/api/orders", (CreateOrder request) => Result.Created(request))
.WithXValidationSupport()
.WithXResultSupport();
WithXValidationSupport() adds ResultEndpointValidationFilter, which resolves IResultEndpointValidator from the
request (AddXResultEndpointValidator() registers ResultEndpointValidator, scoped, with the validator provider and
the default header writer; AddXResultEndpointValidator<T>() replaces it).
Error keys follow the PropertyNamingPolicy of the registered Microsoft.AspNetCore.Http.Json.JsonOptions (the minimal
API options; camelCase by default; a null policy keeps the declared names), as do those of a ValidationException
answered by the middleware. An MVC host that changes its naming policy (AddJsonOptions) configures
Microsoft.AspNetCore.Http.Json.JsonOptions the same way.
ResultEndpointValidator validates each IRequiresValidation argument before the endpoint runs:
- A failure β with or without member errors, a
ValidationException, or aResultExceptionwith its own status β stops the endpoint and is written as problem details (400 with the member errors by default), whatever the order of the filters: the validator returns a complete response, not aResult. - The failures of every argument are merged: errors, headers and extensions accumulate; the status is the first one other than 400 (a validator's 403, 404 or 409 wins over the generic 400), with the title and detail of the failure that set it.
- An
IRequiresValidationargument without a registered validator throwsInvalidOperationExceptionnaming theAddXValidator<β¦>call to add. - Any other exception thrown by a validator is wrapped in an
InvalidOperationExceptionnaming the argument type and index. A cancellation is not a validation failure: it propagates. - The validators receive
HttpContext.RequestAborted, so a validator that queries a database stops when the client goes away. - Every validator registered for a type runs (they are composed); validators are resolved from the request scope, so
they can depend on scoped services (a
DbContextfor a uniqueness check). - A type validated by its DataAnnotations attributes gets a generated validator (Xpandables.Validations), registered by
the generated
services.AddX{Assembly}Validators(), which also registers the assembly's validator classes.
πΊοΈ Minimal API Routing
Modular Endpoints
using Microsoft.AspNetCore.Routing;
public sealed class OrderEndpoints(TimeProvider clock) : MinimalEndpointRoute
{
public override void AddRoutes(IEndpointRouteBuilder app)
{
// Per-request services are handler parameters, resolved for each request.
app.MapGet("/api/orders/{id}", (Guid id, IOrderRepository repository, CancellationToken ct) =>
repository.GetByIdAsync(id, ct))
.WithXResultSupport();
app.MapGet("/api/time", () => Result.Success(clock.GetUtcNow()))
.WithXResultSupport();
}
}
// Program.cs
builder.Services.AddXMinimalEndpointRoutesGenerated(); // generated
var app = builder.Build();
app.UseXMinimalEndpointRoutes(); // maps every registered route
- The generated
AddXMinimalEndpointRoutesGenerated()registers each route once (TryAddEnumerable) as a transientIMinimalEndpointRoute, built by the container, so constructor injection works. UseXMinimalEndpointRoutes()resolves the routes in a scope disposed once they are mapped, and callsAddRouteson each. A route is built once: its constructor takes singletons only. A scoped service captured there would be shared by every request, and already disposed.- Every concrete, non-generic route class of the application is registered (it need not be sealed), and so are the
public routes of the referenced libraries that reference an Xpandables assembly. An abstract or generic route is a
base and is skipped; a concrete base route and its subclass are both mapped, so make a base route abstract. A route
of the application that cannot be registered (private or file-local, nested in a generic type, a struct,
[Obsolete], no public constructor) is reported by warningXSR002. - A route that needs services or startup work also implements
IAddService/IUseService.
Produces and Accepts Annotations
app.MapGet("/api/users/{id}", (Guid id, IUserRepository users, CancellationToken ct) => users.GetByIdAsync(id, ct))
.Produces200OK<User>()
.Produces404NotFound()
.Produces400BadRequest()
.Produces401Unauthorized()
.Produces500InternalServerError();
app.MapPost("/api/users", (CreateUser request) => Result.Created(new User(request.Name)))
.Accepts<CreateUser>()
.Produces201Created<User>()
.Produces409Conflict();
| Method | Metadata |
|---|---|
Accepts<TRequest>() |
request body TRequest, application/json |
Produces200OK() |
200, no body, no content type |
Produces200OK<T>() / Produces201Created<T>() |
200 / 201 with T, application/json |
Produces400BadRequest() |
400 validation problem, application/problem+json |
Produces401Unauthorized(), Produces404NotFound(), Produces405MethodNotAllowed(), Produces409Conflict(), Produces500InternalServerError() |
problem, application/problem+json |
The parameterless methods apply to any IEndpointConventionBuilder (a route group too); the generic ones to a
RouteHandlerBuilder.
OpenAPI 3.2 and generated clients
The annotations are endpoint metadata; the OpenAPI document is generated by your application
(Microsoft.AspNetCore.OpenApi), which targets OpenAPI 3.2 from ASP.NET Core 11. Client generators do not all read 3.2
yet β openapi-generator (its dart and dart-dio generators among others) relies on swagger-parser, which does not
support 3.2 as of November 2026 β so an application whose clients are generated that way keeps 3.1:
builder.Services.AddOpenApi(options => options.OpenApiVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_1);
π Event Context Middleware
builder.Services.AddXEventContextAccessor(); // ICorrelationContextAccessor (Xpandables.Events)
builder.Services.AddXEventContextMiddleware(); // EventContextMiddleware, singleton (the accessor must be a singleton too)
// or: builder.Services.AddXEventContextMiddleware<CustomEventContextMiddleware>();
// Header names, read on each request (IOptionsMonitor: a change applies to the next request)
builder.Services.Configure<EventContextOptions>(options =>
{
options.CorrelationIdHeaderName = "X-Correlation-Id"; // default; "traceparent" is refused
options.CausationIdHeaderName = "X-Causation-Id"; // default
});
var app = builder.Build();
app.UseXEventContextMiddleware(); // or UseXEventContextMiddleware<CustomEventContextMiddleware>()
app.MapPost("/api/orders", (ICorrelationContextAccessor context) =>
{
string? correlationId = context.Current.CorrelationId;
// From the correlation header, else the activity's trace id (32 hex), else a new GUID ("N")
});
For each request, EventContextMiddleware opens an ICorrelationContextAccessor scope holding:
- the correlation identifier: the first value of the correlation header, else the trace id of
Activity.Current(32 hex digits; only a W3C-format activity has one, any other format gives a new GUID), else a new GUID (Nformat) - never thetraceparenttrace context, which tracing keeps separately; it is always echoed in the response under the same header name; - the causation identifier: the first value of the causation header, else
null; it is not echoed.
The identifiers are written to the event tables, whose columns hold 100 characters: a value longer than that, or with
characters outside visible ASCII (spaces included), is ignored β the correlation falls back to the W3C activity's
trace id or a new GUID, the causation is null β and is not echoed back.
UseXEventContextMiddleware() / UseXEventContextMiddleware<T>() throw InvalidOperationException when the
middleware is not registered. Register the middleware early in the pipeline, so downstream components see the context.
π Pipeline Behaviors
The generated handler registration closes the behaviors for each request that asks for them:
using System.Handlers.Generated;
builder.Services
.AddXMediator()
.AddXApplicationHandlers() // the handlers' library
.AddXWebHostHandlers(); // the web host
The validation, unit-of-work and idempotency behaviors, and the Idempotency-Key setters, are closed by the generated
registration of the assembly that references this package: for its own marked requests and for those of the class
libraries it references that do not reference it. An application without this package that handles a marked request,
or references a library that generates a handler registration and declares a public one (a worker host over the
application layer), is error XHG005, once per request and marker. A contracts-only library, or one whose handlers
are registered by hand, generates no registration and is not reported. The closed registrations (TryAddEnumerable,
scoped) can also be called directly:
| Method | Request shape |
|---|---|
AddXValidationBehavior<TRequest, TResponse>() |
IRequest<TResponse> |
AddXValidationBehavior<TRequest>() |
IRequest (no response) |
AddXStreamValidationBehavior<TRequest, TResponse>() |
IStreamRequest<TResponse> |
AddXStreamPagedValidationBehavior<TRequest, TResponse>() |
IStreamPagedRequest<TResponse> |
AddXDataUnitOfWorkBehavior<TRequest, TResponse>() |
IRequest<TResponse> |
AddXDataUnitOfWorkBehavior<TRequest>() |
IRequest (no response) |
AddXIdempotencyBehavior<TRequest, TResponse>() |
IRequest<TResponse> |
AddXIdempotencyBehavior<TRequest>() |
IRequest (no response) |
Validation (every request shape, reference-type requests): the validation registrations also add the request's composite validator, which runs every validator registered with
AddXValidator<TRequest, TValidator>(). A failure throwsMultipleValidationExceptionbefore the handler runs, whichResultMiddlewareanswers with 400 problem details. A request without a validator throwsInvalidOperationExceptionnaming the registration to add. A stream request is validated when it is first enumerated; a paged request when it is first used β cancelling either the request or that first use cancels the validation, and a failed validation is not kept: the next use validates again.Data unit of work (void and response requests): runs the handler in a transaction from the registered
IDataUnitOfWork(Xpandables.Data). The transaction is committed when the handler completes; a failedResultor a handler exception leaves it uncommitted, and its disposal rolls it back. A commit failure surfaces as is, never replaced by a rollback exception. Nested units join the active transaction, and an inner rollback vetoes the outer commit. The behavior requires a registeredIDataUnitOfWork: without one, resolving it throwsInvalidOperationException, so a request that requires a unit of work never runs outside one. A stream request gets none β a transaction cannot span a lazily enumerated stream β and errorXHG004says so.Idempotency (void and response requests implementing
IIdempotentRequestandIRequiresDataUnitOfWork, order 15): commits a command at most once per key and scope. It opens the request's transaction (the unit-of-work behavior joins it), looks the key up and returns the stored response without running the handler, or runs it and stores the response β serialized with the response'sJsonTypeInfofrom the HTTP JSON options, so an AOT application declares it in itsJsonSerializerContextβ in the same transaction as the handler's writes. The pre-behaviors (order 35) run inside that transaction too. A failedResult(4xx or 5xx) or an exception stores nothing. An invalid key isValidationException(400). Entries expire afterIdempotencyOptions.Retention(24 hours; a non-positive retention fails when the host starts).A concurrent duplicate β a client that times out and retries while its first request still runs β is not held back: its handler runs too, and when its save (or a write of its own unique key) fails because the first request committed the key, its transaction is rolled back and
ResultException409 Conflict is thrown. Only its database writes are undone: a side effect outside the database (a payment API, an e-mail) belongs in the transaction, through the outbox, so that it leaves with the commit and never twice.IdempotencyKeyis chosen by the client, so two callers may choose the same one. When a key belongs to a caller, return the caller's identity fromIdempotencyScopeβ a user id, a tenant id, 1 to 200 visible ASCII characters β and each caller gets its own entries: another caller's key runs the handler instead of replaying a response that is not theirs. The default,null, shares one key space between every caller of the request type.The scope never comes from the request: a scope bound from the JSON body lets a caller name another tenant and receive its stored response. Mark it
[JsonIgnore]and set it in the endpoint from the authenticated user:public sealed record PlaceOrder(string Item) : IRequest<Result<Guid>>, IIdempotentRequest, IRequiresDataUnitOfWork { public string IdempotencyKey { get; init; } = ""; [JsonIgnore] public string? IdempotencyScope { get; init; } } app.MapPost("/orders", (PlaceOrder order, ClaimsPrincipal user, IMediator mediator, CancellationToken ct) => mediator.SendAsync<PlaceOrder, Result<Guid>>( order with { IdempotencyScope = user.FindFirstValue(ClaimTypes.NameIdentifier) }, ct)) .WithXIdempotencySupport() .WithXResultSupport();An invalid scope throws
InvalidOperationExceptionbefore any transaction: the application sets it, not the client.Only a response its declared type replays exactly is stored: a subtype of the response type, or a non-generic
Resultcarrying a value, throwsInvalidOperationExceptionand rolls back β declareIRequest<Result<T>>or the exact response type. The behavior owns the request's transaction: inside a transaction begun before it, a replay commits its participant (the caller's transaction stays committable) and a failure propagates as is, without the 409, since the key cannot be read again in the caller's transaction. Entries are keyed by the request type'sToString()(full name, generic arguments by full name); a name longer than 400 characters or not ASCII throwsInvalidOperationException.The store over Xpandables.Data:
builder.Services .AddXData(data => data.UsePostgreSql(connectionString)) .AddXDataIdempotencyStore(options => options.Retention = TimeSpan.FromHours(48)); // Once, at deployment: the table for the database's dialect. string ddl = IdempotencyTableScripts.GetCreateTableScript(SqlDialect.PostgreSql);DataIdempotencyStorewritesIdempotencyEntries(key, request name, scope, status, response JSON, created on, expires on; primary key key + request name + scope; index on the expiry) through the request'sIDataUnitOfWork, so an entry commits or rolls back with the handler's writes. Scripts exist for SQL Server, PostgreSQL, MySQL, Oracle and SQLite; keys and scopes compare case-sensitively on each (binary collations on SQL Server and MySQL). An unscoped key is stored with a single space inScope, a primary key column that cannot beNULL(and Oracle stores an empty string asNULL). Its times are UTC: an entry with anotherDateTimeKindis refused withArgumentException. An entry found expired is deleted at once so its key runs again; the events' retention purge (services.AddXEventRetention(), Xpandables.Events) removes the others once expired, through the registeredIIdempotencyStore, unlessEventRetentionOptions.IdempotencyEntriesis false. Without it, callPurgeExpiredAsync(batchSize)periodically.The
Idempotency-Keyheader:app.MapPost("/orders", (PlaceOrder order, IMediator mediator, CancellationToken cancellationToken) => mediator.SendAsync<PlaceOrder, Result<Guid>>(order, cancellationToken)) .WithXIdempotencySupport() .WithXResultSupport();WithXIdempotencySupport()reads the header into the request through the setter the generatedAddX{Assembly}Handlers()registers for eachIIdempotentRequestwhoseIdempotencyKeyit can set (an accessibleset, or an accessibleiniton a record). For such a request a missing header, two values, or a value that is not 1 to 200 visible ASCII characters is 400 problem details and the endpoint does not run; one value with a comma (a,b) is one key. The setter is looked up by the argument's exact type: a subtype of a registered request is left as it is. A request whose key is get-only computes it itself and needs no header. A key that cannot be set (aniniton a class, aprivate set) still gets the behavior but no setter: the header is ignored and an empty key is 400 at the behavior. AddWithXIdempotencySupport()beforeWithXValidationSupport(): endpoint filters run in the order they are added, so the validation sees the request with its key.Authorization (Xpandables.Handlers):
AddXHttpContextPrincipalAccessor()registersHttpContextPrincipalAccessor(singleton, TryAdd, withAddHttpContextAccessor()): the request'sHttpContext.User. Outside an HTTP request β a background service dispatching through the mediator β there is no user, and a request that requires authorization is refused as unauthenticated.AddXAuthorizationPolicyEvaluator()registersAuthorizationServicePolicyEvaluator(scoped, TryAdd, withAddAuthorizationCore()): it evaluates a request'sPolicyNamewithIAuthorizationService, passing the request as the resource, so resource-based authorization handlers receive it. Configure the policies withAddAuthorization/AddAuthorizationBuilderas usual.
π§© IUseService
using Microsoft.AspNetCore.Builder;
public sealed class SeedDataService : UseService
{
public override int Order => 100;
public override async Task UseServicesAsync(WebApplication application, CancellationToken ct)
{
await SeedDatabaseAsync(application.Services, ct);
}
}
// Program.cs β generated: runs every IUseService of the application in ascending Order
await app.UseXServicesGeneratedAsync();
UseXServicesGenerated()callsUseServices(application)andUseXServicesGeneratedAsync(cancellationToken)awaitsUseServicesAsync(application, cancellationToken)on a new instance of every implementation, in ascendingOrder.- An implementation needs an accessible parameterless constructor and resolves what it needs from
application.Services; one that the generated code cannot instantiate is reported by warningXSR001. UseServiceis the base class:Orderis 0,UseServicesdoes nothing, andUseServicesAsynccallsUseServices.
π οΈ Event Operations Endpoints
The dead letters of Xpandables.Events, over HTTP, for operators:
builder.Services.AddAuthorizationBuilder().AddPolicy("ops", policy => policy.RequireRole("operator"));
app.MapXEventOperations("ops"); // under /_ops/events; the policy is required
| Endpoint | Answer |
|---|---|
GET outbox |
{"pending": n, "parked": n} (MaxSchedulerRetries of the registered SchedulerOptions) |
GET outbox/parked?skip=&take= |
The parked outbox events (ParkedOutboxEvent), take 1 to 1000 (50 by default) |
POST outbox/parked/{eventId}/requeue |
204, or 404 when no such parked event |
POST outbox/parked/requeue |
{"count": n} |
DELETE outbox/parked?olderThan= |
{"count": n}; olderThan (ISO 8601) is required |
GET inbox/suspended?consumer=&skip=&take= |
The suspended inbox receipts (SuspendedInboxEvent), of one consumer or of all |
POST inbox/suspended/{eventId}/requeue?consumer= |
204 or 404; consumer is required |
POST inbox/suspended/requeue?consumer= |
{"count": n} |
DELETE inbox/suspended?olderThan=&consumer= |
{"count": n} |
The policy name is required: no anonymous operations endpoint can be mapped. A requeue or a purge done twice changes
nothing more. The handlers are plain request delegates writing source-generated JSON (Native AOT); an invalid query
parameter is a 400 with a problem body. The saga operations are in Xpandables.AspNetCore.Sagas (MapXSagaOperations).
π§° Other Helpers
JsonSerializerOptions json = httpContext.GetJsonSerializerOptions(); // the HTTP JSON options
string? contentType = httpContext.GetContentType(); // declared for the current status, or null
string orJson = httpContext.GetContentType("application/json"); // with a default
Encoding encoding = httpContext.GetEncoding(); // charset of the content type, else UTF-8
builder.Services.AddXLazyResolved(); // Lazy<T> injected from the container
GetContentType() returns, with an endpoint, the first content type the endpoint declares for the current response
status (so .Produces<T>().ProducesProblem(500) gives a success the type of Produces<T>), or null when it declares
none for that status; without an endpoint, the response's content type.
AddXLazyResolved() registers Lazy<> as LazyResolved<> (transient): the value is taken from the container on the
first read of Lazy<T>.Value, which must happen while the resolving scope is alive.
π©Ί Generator Diagnostics
| Id | Severity | Reported for |
|---|---|---|
XSR001 |
Warning | an IAddService / IUseService the generated code cannot instantiate (nested in a generic type, [Obsolete], no accessible parameterless constructor, required members without [SetsRequiredMembers]) |
XSR002 |
Warning | an IMinimalEndpointRoute that cannot be registered (private or file-local, nested in a generic type, a struct, [Obsolete], no public constructor) |
XHG004 |
Error | a request marker no built-in behavior applies to that request shape (IRequiresDataUnitOfWork or IIdempotentRequest on a stream, paged or value-type request, ICacheableRequest on a stream or paged request, or IRequiresValidation on a value type) |
XHG005 |
Error | an application without this package handling a request carrying IRequiresValidation, IRequiresDataUnitOfWork or IIdempotentRequest, or referencing a library that generates a handler registration and declares one (once per request and marker, naming the library) |
XHG007 |
Error | a request implementing IIdempotentRequest without IRequiresDataUnitOfWork: its response must be stored in the handler's transaction |
π§ All DI Methods
| Method | Lifetime | Description |
|---|---|---|
AddXJsonSerializerOptions(configure) |
singleton | Library JSON metadata, then yours; registers JsonSerializerOptions and IJsonSerializerContext (TryAdd) |
AddXMinimalEndpointRoutesGenerated() |
transient | (generated) Registers the application's IMinimalEndpointRoute implementations |
AddXServicesGenerated() / AddXServicesGenerated(configuration) |
β | (generated) Runs the application's IAddService implementations |
AddXResultMiddleware() |
singleton | Registers ResultMiddleware |
AddXResultProblemDetails() |
singleton | AddProblemDetails(), then the result-aware IProblemDetailsService (replace) |
AddXResultHeaderWriter() / AddXResultHeaderWriter<T>() |
singleton / scoped | Header writer (TryAdd / replace) |
AddXResultEndpointValidator() / AddXResultEndpointValidator<T>() |
scoped | Endpoint argument validator (TryAdd / replace); the parameterless one adds the validator provider and the header writer |
AddXValidationBehavior<TRequest>() / <TRequest, TResponse>() |
scoped | Closed validation behavior (void / response request) |
AddXStreamValidationBehavior<TRequest, TResponse>() / AddXStreamPagedValidationBehavior<TRequest, TResponse>() |
scoped | Closed validation behavior (stream / paged request) |
AddXDataUnitOfWorkBehavior<TRequest>() / <TRequest, TResponse>() |
scoped | Closed unit-of-work behavior (void / response request) |
AddXIdempotencyBehavior<TRequest>() / <TRequest, TResponse>() |
scoped | Closed idempotency behavior (void / response request), with IdempotencyOptions |
AddXDataIdempotencyStore() |
scoped | IIdempotencyStore over Xpandables.Data (DataIdempotencyStore, TryAdd), with IdempotencyOptions |
AddXHttpContextPrincipalAccessor() |
singleton | IPipelinePrincipalAccessor over HttpContext.User (TryAdd) |
AddXAuthorizationPolicyEvaluator() |
scoped | IPipelinePolicyEvaluator over IAuthorizationService (TryAdd; adds the authorization services) |
AddXEventContextMiddleware() / AddXEventContextMiddleware<T>() |
singleton / transient | Registers the event context middleware |
AddXLazyResolved() |
transient | Registers Lazy<T> resolution |
WithXResultSupport() |
β | Adds ResultEndpointFilter and the result response metadata to an endpoint |
WithXValidationSupport() |
β | Adds ResultEndpointValidationFilter to an endpoint |
UseXResultMiddleware() |
β | Adds ResultMiddleware to the pipeline |
UseXEventContextMiddleware() / UseXEventContextMiddleware<T>() |
β | Adds the event context middleware |
UseXMinimalEndpointRoutes() |
β | Maps the registered routes |
MapXEventOperations(policy, prefix) |
β | Maps the operations endpoints of the outbox and inbox dead letters, behind the policy |
UseXServicesGenerated() / UseXServicesGeneratedAsync() |
β | (generated) Runs the application's IUseService implementations |
Accepts<T>(), Produces200OK<T>(), Produces400BadRequest(), etc. |
β | OpenAPI metadata annotations |
π¦ Package Contents
| Namespace | Types |
|---|---|
Microsoft.AspNetCore |
EventContextMiddleware, EventContextOptions |
Microsoft.AspNetCore.Http |
ResultMiddleware, ResultEndpointFilter, ResultEndpointValidationFilter, ResultHeaderWriter, ResultEndpointValidator, ResultProblemDetailsService, ResultExtensions, HttpContextExtensions, IResultHeaderWriter, IResultEndpointValidator |
Microsoft.AspNetCore.Routing |
IMinimalEndpointRoute, MinimalEndpointRoute |
Microsoft.AspNetCore.Builder |
IUseService, UseService |
System.Handlers |
ValidationBehavior<TRequest>, ValidationBehavior<TRequest, TResponse>, StreamValidationBehavior<TRequest, TResponse>, PagedValidationBehavior<TRequest, TResponse>, DataUnitOfWorkBehavior<TRequest>, DataUnitOfWorkBehavior<TRequest, TResponse>, IdempotencyBehavior<TRequest>, IdempotencyBehavior<TRequest, TResponse>, IdempotencyOptions, DataIdempotencyStore, IdempotencyTableScripts, HttpContextPrincipalAccessor, AuthorizationServicePolicyEvaluator |
Microsoft.Extensions.DependencyInjection |
AspNetCoreServiceCollectionExtensions, AspNetCoreBehaviorServiceCollectionExtensions |
π License
Apache License 2.0 β see the LICENSE file for details.
<div align="center">
Built with β€οΈ using .NET 11
</div>
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Xpandables.Data (>= 11.0.0)
- Xpandables.Events (>= 11.0.0)
- Xpandables.Generators (>= 11.0.0)
- Xpandables.Handlers (>= 11.0.0)
- Xpandables.Validations (>= 11.0.0)
NuGet packages (4)
Showing the top 4 NuGet packages that depend on Xpandables.AspNetCore.Net:
| Package | Downloads |
|---|---|
|
Xpandables.AspNetCore.Results
Package Description |
|
|
Xpandables.AspNetCore.AsyncPaged
ASP.NET Core integration of Xpandables.AsyncPaged: an IResult and an endpoint filter that stream IAsyncPagedEnumerable<T> as JSON with its pagination; Native AOT compatible. |
|
|
Xpandables.AspNetCore.Mvc
ASP.NET Core MVC integration of Xpandables results: controller result filters and options. Not Native AOT compatible, as ASP.NET Core MVC. |
|
|
Xpandables.AspNetCore.Sagas
ASP.NET Core operations endpoints of Xpandables.Sagas: query saga instances, read their history, cancel, retry and draw their definitions, behind a required authorization policy; Native AOT compatible. |
GitHub repositories
This package is not used by any popular GitHub repositories.