Xpandables.AspNetCore.AsyncPaged 11.0.0

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

πŸ“¦ AspNetCore.AsyncPaged

License .NET Version NuGet Version NuGet Downloads

ASP.NET Core integration for streaming large or paged datasets asynchronously as JSON β€” an IResult, an endpoint filter, and the extensions that wire them

Overview β€’ Getting Started β€’ Streaming Responses β€’ Endpoint Filter β€’ Requests β€’ JSON Metadata β€’ Failures


πŸ“‹ Overview

Xpandables.AspNetCore.AsyncPaged bridges IAsyncPagedEnumerable<T> (Xpandables.AsyncPaged) into ASP.NET Core:

  • AsyncPagedResult<TResult> β€” an IResult that streams the sequence as { "pagination": { … }, "items": [ … ] } straight to the response PipeWriter, flushing as it goes, then disposes the sequence;
  • ToResult(jsonSerializerContext) β€” the extension that creates it;
  • AsyncPagedEndpointFilter<TResult> β€” an IEndpointFilter that turns an IAsyncPagedEnumerable<TResult> returned by an endpoint into that result;
  • WithXAsyncPagedSupport<…>() β€” the extensions that add the filter to an endpoint or a route group.

AddXAsyncPaged() registers a continuation-token protector over Data Protection and the page-size limits (Pagination Requests). The package serializes through the IJsonSerializerContext registered by AddXJsonSerializerOptions() (Xpandables.AspNetCore.Net).


πŸš€ Getting Started

dotnet add package Xpandables.AspNetCore.AsyncPaged
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

builder.Services.AddXJsonSerializerOptions(options =>
    options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default));

var app = builder.Build();

app.MapGet("/api/orders", (IOrderQueries orders, CancellationToken ct) => orders.GetPagedAsync(ct))
   .WithXAsyncPagedSupport<Order>();

🌊 Streaming Responses

ToResult

using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

app.MapGet("/api/orders", (IOrderQueries orders, IJsonSerializerContext json, CancellationToken ct) =>
{
    IAsyncPagedEnumerable<Order> page = orders.GetPagedAsync(ct);

    // Wrap in a streaming IResult; the context resolves the item type's metadata
    return page.ToResult(json);
});
// Response: { "pagination": { … }, "items": [ … ] } streamed asynchronously with Transfer-Encoding: chunked

ToResult and the AsyncPagedResult<TResult> constructor throw ArgumentNullException for a null sequence or context.

AsyncPagedResult<TResult>

IAsyncPagedEnumerable<Order> page = orders.GetPagedAsync(ct);
var result = new AsyncPagedResult<Order>(page, httpContext.RequestServices.GetRequiredService<IJsonSerializerContext>());
await result.ExecuteAsync(httpContext);

ExecuteAsync:

  1. sets Content-Type, when the response has none yet, to the content type the endpoint declares (for example with .Produces<T>()) for the current status code, with charset=utf-8 when it has no charset, otherwise application/json; charset=utf-8;
  2. resolves JsonTypeInfo<TResult> from the IJsonSerializerContext (InvalidOperationException when the context has no metadata for TResult: answered 500 and rethrown, like a serialization failure, and the sequence is disposed);
  3. computes the pagination; when it has a continuation token, sets Link: <url>; rel="next", the request's absolute URL with the token parameter replaced (continuationToken, or AsyncPagedLinkOptions.ContinuationTokenParameter through services.Configure<AsyncPagedLinkOptions>(…)), the other parameters kept;
  4. serializes with JsonSerializer.SerializeAsyncPaged to Response.BodyWriter, observing HttpContext.RequestAborted: the pagination is computed first, then the items are written and flushed every 16 KB and whenever the sequence waits (see Xpandables.AsyncPaged, "JSON Serialization"), so the client receives items while the sequence is still being read; if the client goes away, serialization stops at the next flush;
  5. disposes the sequence once serialization ends, successfully or not β€” an IResult has no other disposal hook, and the sequence commonly owns a database reader, an HTTP response or a PipeReader.

The item type's own JSON metadata applies to the items; the pagination object is written without metadata, its four members always present in camelCase whatever the options (totalCount, pageSize, currentPage, continuationToken).

JSON Lines (Accept: application/jsonl)

A client that asks for JSON Lines β€” Accept: application/jsonl (or application/x-ndjson) with a quality no lower than any JSON it also accepts β€” gets the items one per line instead of the paged object, written with .NET 11 JsonSerializer.SerializeAsyncEnumerable(…, topLevelValues: true) (the first item leaves while the sequence still works; a client that goes away stops the serialization):

HTTP/1.1 200 OK
Content-Type: application/jsonl
X-Total-Count: 42
X-Page-Size: 10
X-Current-Page: 1
Link: <https://api.example.test/orders?continuationToken=…>; rel="next"
Vary: Accept

{"id":1,"name":"first"}
{"id":2,"name":"second"}
  • The pagination known when the response starts travels in headers, each sent when its value is known: X-Total-Count, X-Page-Size, X-Current-Page, and the token in Link as above. Without them the client's pagination is empty.
  • Without an Accept, or with one that prefers JSON, the paged object is written as before. Every answer carries Vary: Accept; a 400 or 500 answer carries no pagination header.
  • Xpandables.Rests (Accept = RestSettings.ContentType.JsonLines on a paged stream request) and HttpResponseMessage.ReadFromJsonAsAsyncPagedEnumerable (Xpandables.AsyncPaged) read both forms.

πŸ”§ Endpoint Filter

Automatic interception

using Microsoft.AspNetCore.Http;

app.MapGet("/api/orders", (IOrderQueries orders, CancellationToken ct) =>
{
    // Return IAsyncPagedEnumerable<T> directly
    return orders.GetPagedAsync(ct);
})
.WithXAsyncPagedSupport<Order>(); // adds AsyncPagedEndpointFilter<Order>

After the endpoint runs, AsyncPagedEndpointFilter<TResult> replaces its result when it is an IAsyncPagedEnumerable<TResult> with an AsyncPagedResult<TResult> built from the IJsonSerializerContext resolved from the request services (InvalidOperationException when none is registered). Any other result, including null and a paged sequence of another item type, passes through unchanged. When the filter cannot build the streaming result (no IJsonSerializerContext), it disposes the sequence before the exception leaves.

WithXAsyncPagedSupport also declares the responses to OpenAPI: 200, application/json, AsyncPagedEnvelope<TResult> (pagination and items), and 400, application/problem+json, ProblemDetails (a continuation token or a page size the client got wrong).

Registration overloads

// A route handler
app.MapGet("/api/orders", handler)
   .WithXAsyncPagedSupport<Order>();

// Any endpoint convention builder (a route group, for instance)
app.MapGroup("/api/orders")
   .WithXAsyncPagedSupport<RouteGroupBuilder, Order>();

Both return the builder for chaining. They live in Microsoft.Extensions.DependencyInjection.AsyncPagedEndpointExtensions.


🎫 Pagination Requests

AddXAsyncPaged(configureLimits?) registers:

  • an ICursorTokenProtector over ASP.NET Core Data Protection (AddDataProtection()): continuation tokens are authenticated and encrypted with the application's key ring, so a client can neither read nor forge a position (a protector registered before the call is kept);
  • PaginationLimits as options (IOptions<PaginationLimits>; MaxPageSize 1000 and DefaultPageSize 50 by default), validated when the host starts: both sizes positive and the default no larger than the maximum, otherwise an OptionsValidationException.

The key ring signs every token: an application running on several instances shares one persisted key ring between them (PersistKeysTo… and the same SetApplicationName); otherwise a token issued by another instance, or before a restart that lost the keys, does not verify and is answered 400. So is a token whose key has left the ring (deleted or revoked).

The endpoint below pages an EF Core query with the ToAsyncPagedEnumerable(cursorOptions, options) overload of Xpandables.EntityFramework, which counts the total with LongCountAsync.

using Microsoft.EntityFrameworkCore; // Xpandables.EntityFramework: counts with LongCountAsync

builder.Services.AddXAsyncPaged(limits => limits.MaxPageSize = 200);

app.MapGet("/api/orders", (int? pageSize, string? continuationToken, AppDbContext db,
        IOptions<PaginationLimits> limits, ICursorTokenProtector protector) =>
    {
        PageRequest page = Pagination.FromRequest(pageSize, continuationToken, limits.Value, protector);
        return db.Orders
            .Take(page.PageSize)
            .ToAsyncPagedEnumerable(OrderCursor.WithAppliedToken(page.Token), new PaginationOptions { Protector = protector });
    })
   .WithXAsyncPagedSupport<Order>();

A CursorTokenException (a token that does not read, was altered, or was issued for another cursor) or a PageSizeOutOfRangeException (a page size of zero or less) is answered 400 with application/problem+json (type, title, status, detail) β€” thrown by the endpoint, the filter answers it; thrown by a deferred sequence when the result starts, the result answers it before writing anything. It is not rethrown.


🧾 JSON Metadata and Native AOT

AsyncPagedResult<TResult> serializes through the IJsonSerializerContext that AddXJsonSerializerOptions() (Xpandables.AspNetCore.Net) registers. For Native AOT, insert the application's source-generated context into its resolver chain:

builder.Services.AddXJsonSerializerOptions(options =>
    options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default));

The context declares the item type and, for an endpoint that returns the sequence to the filter, the declared return type too: the Request Delegate Generator resolves the metadata of every declared return type when it builds the endpoints, and a missing one fails every endpoint of the application.

[JsonSerializable(typeof(Order))]
[JsonSerializable(typeof(IAsyncPagedEnumerable<Order>))]
[JsonSerializable(typeof(AsyncPagedEnvelope<Order>))] // for OpenAPI document generation
internal sealed partial class AppJsonContext : JsonSerializerContext;

The package itself uses no reflection: item metadata comes from the context, and the pagination is written by hand.


🚨 Failures while streaming

The serializer computes the pagination and reads the first item before writing anything, then flushes the page as it goes (every 16 KB, and whenever the sequence waits), so the response starts before the sequence is fully read:

  • a failure before the first flush answers 500 (a sequence that waits after its first item, such as a database reader, has started the response by then), taking back the content type the result set and keeping the headers set before it (a correlation id), and the exception is rethrown, reaching ResultMiddleware (UseXResultMiddleware, Xpandables.AspNetCore.Net), which answers with the status it maps the exception to and the problem details; the Link header is removed;
  • a failure after it aborts the connection: the client sees a broken response, never a truncated page that looks complete;
  • once the client has aborted the request (HttpContext.RequestAborted is cancelled), any exception passes through untouched: the response is neither cleared nor aborted.

In every case the sequence is disposed before the exception leaves ExecuteAsync.


πŸ“¦ Package Contents

Namespace Types
Microsoft.AspNetCore.Http AsyncPagedResult<TResult>, AsyncPagedExtensions, AsyncPagedEndpointFilter<TResult>, AsyncPagedLinkOptions, AsyncPagedEnvelope<TResult>
Microsoft.Extensions.DependencyInjection AsyncPagedEndpointExtensions (WithXAsyncPagedSupport), AsyncPagedServiceCollectionExtensions (AddXAsyncPaged)

πŸ“„ 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

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
10.0.2 164 3/15/2026
10.0.1 136 2/20/2026
10.0.0 159 1/9/2026