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
                    
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.Net" 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.Net" Version="11.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Xpandables.AspNetCore.Net" />
                    
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.Net --version 11.0.0
                    
#r "nuget: Xpandables.AspNetCore.Net, 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.Net@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.Net&version=11.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Xpandables.AspNetCore.Net&version=11.0.0
                    
Install as a Cake Tool

πŸ“¦ AspNetCore.Net

License .NET Version NuGet Version NuGet Downloads

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:

  • ResultMiddleware turns unhandled exceptions into problem details, and ResultEndpointFilter writes a returned Result as its value or as problem details;
  • ResultEndpointValidationFilter validates the IRequiresValidation arguments of an endpoint before it runs;
  • EventContextMiddleware propagates the correlation and causation identifiers of a request;
  • IMinimalEndpointRoute groups routes in modules, and IUseService runs 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() and AddX{Assembly}Handlers() are emitted in your application by Xpandables.Generators; nothing is discovered by scanning assemblies.

  • JSON metadata. AddXJsonSerializerOptions adds the library's own source-generated metadata (ElementCollectionContext, ElementEntryContext) to the HTTP JSON options, then applies your configuration, and registers those options as JsonSerializerOptions and as an IJsonSerializerContext (TryAdd). Add your own context for your payloads, including every Result and Result<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 DateOnly and TimeOnly natively: no converter to add.

  • Validators are registered explicitly with AddXValidator<TArgument, TValidator>() (Xpandables.Validations), or by the generated AddX{Assembly}Validators().

  • Handlers are statically resolvable. The Request Delegate Generator analyses each Map* call where it is written, including inside an IMinimalEndpointRoute. Pass a lambda or a method group directly to Map*: a delegate held in a variable or returned from a factory produces RDG002 and falls back to the reflection-based RequestDelegateFactory, which does not survive ahead-of-time compilation.

  • One open-generic registration remains: AddXLazyResolved() registers Lazy<>, 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() and AddXEventContextMiddleware<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:

  1. the registered IResultHeaderWriter (or, when none is registered, the default ResultHeaderWriter) writes the status and the result's headers; once the response has started, nothing more is written;
  2. IProblemDetailsService.TryWriteAsync writes the problem details built by result.ToProblemDetails(httpContext) (see Result to Problem Details);
  3. when no problem details service is registered, or none of its writers accepts the request (a client that accepts only text/html), TypedResults.Problem writes them as application/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) and type (https://httpstatuses.io/{status});
  • problem details that carry nothing but the exception β€” ASP.NET Core's UseExceptionHandler supplies a bare 500 β€” are rebuilt from the exception with the mapping above, so UseExceptionHandler answers with the exception's mapped status too. A status the application chose (ExceptionHandlerOptions.StatusCodeSelector, an IExceptionHandler) and problem details it filled itself are kept;
  • the response gets the status, application/problem+json unless a content type is already set, Cache-Control: no-cache, no-store, must-revalidate and Pragma: no-cache;
  • the registered IProblemDetailsWriters are tried in order; TryWriteAsync returns false when none accepts the request, WriteAsync throws InvalidOperationException.

Result Endpoint Filter

WithXResultSupport() adds ResultEndpointFilter to an endpoint (or a route group):

  • a Result that 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.ThrowOnBadRequest is false, the default outside development; in development set it to false to 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 a ResultException with 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 a Result.
  • 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 IRequiresValidation argument without a registered validator throws InvalidOperationException naming the AddXValidator<…> call to add.
  • Any other exception thrown by a validator is wrapped in an InvalidOperationException naming 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 DbContext for 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 transient IMinimalEndpointRoute, built by the container, so constructor injection works.
  • UseXMinimalEndpointRoutes() resolves the routes in a scope disposed once they are mapped, and calls AddRoutes on 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 warning XSR002.
  • 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 (N format) - never the traceparent trace 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 throws MultipleValidationException before the handler runs, which ResultMiddleware answers with 400 problem details. A request without a validator throws InvalidOperationException naming 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 failed Result or 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 registered IDataUnitOfWork: without one, resolving it throws InvalidOperationException, 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 error XHG004 says so.

  • Idempotency (void and response requests implementing IIdempotentRequest and IRequiresDataUnitOfWork, 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's JsonTypeInfo from the HTTP JSON options, so an AOT application declares it in its JsonSerializerContext β€” in the same transaction as the handler's writes. The pre-behaviors (order 35) run inside that transaction too. A failed Result (4xx or 5xx) or an exception stores nothing. An invalid key is ValidationException (400). Entries expire after IdempotencyOptions.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 ResultException 409 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.

    IdempotencyKey is chosen by the client, so two callers may choose the same one. When a key belongs to a caller, return the caller's identity from IdempotencyScope β€” 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 InvalidOperationException before 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 Result carrying a value, throws InvalidOperationException and rolls back β€” declare IRequest<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's ToString() (full name, generic arguments by full name); a name longer than 400 characters or not ASCII throws InvalidOperationException.

    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);
    

    DataIdempotencyStore writes IdempotencyEntries (key, request name, scope, status, response JSON, created on, expires on; primary key key + request name + scope; index on the expiry) through the request's IDataUnitOfWork, 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 in Scope, a primary key column that cannot be NULL (and Oracle stores an empty string as NULL). Its times are UTC: an entry with another DateTimeKind is refused with ArgumentException. 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 registered IIdempotencyStore, unless EventRetentionOptions.IdempotencyEntries is false. Without it, call PurgeExpiredAsync(batchSize) periodically.

    The Idempotency-Key header:

    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 generated AddX{Assembly}Handlers() registers for each IIdempotentRequest whose IdempotencyKey it can set (an accessible set, or an accessible init on 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 (an init on a class, a private set) still gets the behavior but no setter: the header is ignored and an empty key is 400 at the behavior. Add WithXIdempotencySupport() before WithXValidationSupport(): endpoint filters run in the order they are added, so the validation sees the request with its key.

  • Authorization (Xpandables.Handlers):

    • AddXHttpContextPrincipalAccessor() registers HttpContextPrincipalAccessor (singleton, TryAdd, with AddHttpContextAccessor()): the request's HttpContext.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() registers AuthorizationServicePolicyEvaluator (scoped, TryAdd, with AddAuthorizationCore()): it evaluates a request's PolicyName with IAuthorizationService, passing the request as the resource, so resource-based authorization handlers receive it. Configure the policies with AddAuthorization / AddAuthorizationBuilder as 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() calls UseServices(application) and UseXServicesGeneratedAsync(cancellationToken) awaits UseServicesAsync(application, cancellationToken) on a new instance of every implementation, in ascending Order.
  • 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 warning XSR001.
  • UseService is the base class: Order is 0, UseServices does nothing, and UseServicesAsync calls UseServices.

πŸ› οΈ 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

⬆ back to top

</div>

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 (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.

Version Downloads Last Updated
11.0.0 0 11/29/2026
10.0.2 198 3/15/2026
10.0.1 145 2/20/2026
10.0.0 156 1/9/2026