Wiaoj.Pagination.AspNetCore 0.5.2-alpha

This is a prerelease version of Wiaoj.Pagination.AspNetCore.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Wiaoj.Pagination.AspNetCore --version 0.5.2-alpha
                    
NuGet\Install-Package Wiaoj.Pagination.AspNetCore -Version 0.5.2-alpha
                    
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="Wiaoj.Pagination.AspNetCore" Version="0.5.2-alpha" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Wiaoj.Pagination.AspNetCore" Version="0.5.2-alpha" />
                    
Directory.Packages.props
<PackageReference Include="Wiaoj.Pagination.AspNetCore" />
                    
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 Wiaoj.Pagination.AspNetCore --version 0.5.2-alpha
                    
#r "nuget: Wiaoj.Pagination.AspNetCore, 0.5.2-alpha"
                    
#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 Wiaoj.Pagination.AspNetCore@0.5.2-alpha
                    
#: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=Wiaoj.Pagination.AspNetCore&version=0.5.2-alpha&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Wiaoj.Pagination.AspNetCore&version=0.5.2-alpha&prerelease
                    
Install as a Cake Tool

Wiaoj.Pagination.AspNetCore

Int64 migration: use PageParameters paging directly in Minimal API handlers when page/size are optional. It retains page 1/size 20 defaults, reads Int64 pages and bounded Int32 sizes, and implicitly converts to PageRequest. Do not annotate this custom binder with AsParameters. The explicit [AsParameters] PageRequest constructor binds required fields; OpenAPI describes required fields without claiming they have defaults. Link page factories now receive long and metadata page schemas are int64; size remains int32.

Pagination selects the relations, page/cursor parameters and directions; Rfc8288LinkHeaderBuilder remains the public facade and delegates header formatting to Wiaoj.Http.LinkHeader.BuildPaging. No canonical sorting is applied. The request's decoded query pairs use Wiaoj.Http.AspNetCore.ReadDecodedQuery and the core package's URI query replacement. ETag hashing and conditional response policy stay in Pagination; formatting and weak comparison use Wiaoj.Http.EntityTag. Both HTTP packages are .NET 11 dependencies included in the same libraries release train.

Generated links include PathBase and preserve repeated filter values individually. Reserved component data (&, =, #, +, %) is encoded rather than becoming URI syntax or being joined into one comma-separated value. Existing page/cursor/direction keys are replaced case-insensitively at their first position. This deliberately corrects the old multi-value/escaping behavior; safe single-value output remains semantically equivalent. Page numbers and Link callbacks use Int64, including next/last values beyond Int32. At long.MaxValue the metadata has no next page, so incrementing cannot wrap.

Run the HTTP and pagination regression solution with the .NET 11 SDK: dotnet test --solution .github/test-filters/http-pagination.slnf -c Release. Existing pagination/OpenAPI tests remain separate; real HTTP/1.1 and HTTP/2 tests follow generated links including repeated/reserved query data.

ASP.NET Core integration for the Wiaoj Pagination ecosystem, providing RFC 8288 Web Linking and SIMD-accelerated XxHash3 ETag evaluation with HTTP 304 Not Modified handling.

Extension methods are exposed directly under the Microsoft.AspNetCore.Builder namespace for fluent Minimal API routing.


Features

  • RFC 8288 Web Linking: Automatically formats and appends standard HTTP Link headers (rel="first", rel="prev", rel="next", rel="last") for both offset and keyset pagination.
  • SIMD-Accelerated ETag Caching: Generates high-throughput weak ETags (W/"...") using XxHash3 (30+ GB/s) and cryptographic strong ETags using Sha256Hash.
  • Automatic 304 Not Modified Handling: Revalidates GET and HEAD responses with If-None-Match. On an explicitly mapped, read-only QUERY endpoint, a matching If-None-Match returns 412 Precondition Failed for the representation selected by the request body. The filter does not enforce mutation preconditions or add QUERY routing or caching.
  • Endpoint Filter: Provides a pre-allocated singleton instance for default .WithPagination() routes.

Note: Pagination state (totalCount, pageNumber, pageSize, totalPages, hasPrevious, hasNext) is exposed exclusively via the response body's metadata object, not via a separate header. This avoids duplicating the same data across two channels — see PagedResult<T> and PageMetadata.


Installation

dotnet add package Wiaoj.Pagination.AspNetCore

Usage Examples

1. Minimal API Integration

Add .WithPagination() to any endpoint returning PagedResult<T> or CursorResult<T>:

using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Wiaoj.Pagination;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Offset pagination with automatic headers and ETag
app.MapGet("/api/products", async (AppDbContext db, [AsParameters] PageRequest request, CancellationToken ct) =>
{
    return await db.Products
        .AsNoTracking()
        .OrderBy(p => p.Id)
        .ToPagedResultAsync(request, ct);
})
.WithPagination();

// Keyset pagination with automatic headers and ETag
app.MapGet("/api/orders", async (AppDbContext db, CursorParameters paging, CancellationToken ct) =>
{
    return await db.Orders
        .AsNoTracking()
        .OrderByDescending(o => o.Id)
        .ToCursorResultAsync(paging, o => o.Id, ct);
})
.WithPagination();

app.Run();

How the paging parameters are bound is not stylistic.

For keyset, take CursorParameters. It binds cursor, limit and direction from the query string and converts implicitly to CursorRequest, so it goes straight into ToCursorResultAsync.

Neither alternative works, in opposite directions:

  • A bare CursorRequest request binds from a single composite value — ?request=cursor:limit:direction — because the type is ISpanParsable<T>. It rejects the ?cursor=…&direction=… form with 400, which is exactly the form this package's own Link headers emit. The first page works, then rel="next" returns 400.
  • [AsParameters] CursorRequest binds through the record's constructor, where the cursor has no default — so the cursor becomes a required query value and the request for the first page, the one that carries no cursor yet, returns 400. Giving it a default does not fix it: minimal APIs cannot express an optional parameter of a custom struct type, and the endpoint fails to build at all.

PageRequest has no such trap — every one of its constructor parameters has a default — so [AsParameters] PageRequest is correct for offset paging.


2. Configuration

Set the defaults once for the application:

builder.Services.AddPagination(pagination =>
    pagination.AddAspNetCoreDefaults(options => options.EnableETag = false));

Every .WithPagination() endpoint then uses them. An endpoint that differs states only the difference — its callback applies on top of the application's settings, not on top of fresh defaults:

app.MapGet("/api/logs", ...)
   .WithPagination(options => options.EnableLinkHeaders = false);   // ETag stays off, from the application

Settings layer: library defaults → AddAspNetCoreDefaults → the endpoint. Selecting ASP.NET defaults is optional; an application that never selects them keeps the library defaults. The OpenAPI document is resolved the same way from the same metadata, so it never advertises an ETag the application turned off.


3. Responses that carry more than the page

A paged response is often an envelope — a workspace view with summaries beside the rows — so it cannot be a PagedResult<T>. Say at the endpoint where its metadata is:

internal sealed record WorkspaceResponse(
    ProjectSummary Project,
    IReadOnlyList<KeyRow> Items,
    PageMetadata Metadata);

app.MapGet("api/v1/applications/{applicationId}/workspace", Handle)
   .WithPagination<WorkspaceResponse>(response => response.Metadata);

The response stays a plain record and implements nothing from this library — how an endpoint is paginated is a fact about the endpoint, not about the contract type. Use a CursorMetadata accessor for a keyset envelope.

The declaration is checked when the endpoint is built: a TResponse that does not appear in the handler's return type throws there, rather than leaving an endpoint that silently sends no Link header. Union return types (Results<Ok<WorkspaceResponse>, ProblemHttpResult>) are seen through, and the problem branch is left alone.

Without this, .WithPagination() on an envelope endpoint does nothing — the filter only acts on a result it recognises as a page.

Handlers returning IResult

The paging style is read from the handler's return type. IResult says nothing, so the OpenAPI document would describe no paging at all. State the style instead:

app.MapGet("api/v1/assets", async Task<IResult> (...) => TypedResults.Ok(window))
   .WithPagination(PaginationStyle.Cursor);

Prefer a typed return (Results<Ok<CursorResult<T>>, ProblemHttpResult>) where one is available — it needs no statement. Where one is given, it is checked rather than trusted, so it cannot drift from what the endpoint serves:

Where What fails
Endpoint build A readable return type that serves the other style, or no page at all
Each response An opaque handler returning a page of the other style — InvalidOperationException. A non-page response (a problem, a redirect) passes.
OpenAPI document A Produces<T>() response type that serves the other style

Use Rfc8288LinkHeaderBuilder directly in custom middlewares or controllers:

using Wiaoj.Pagination.AspNetCore.Linking;

// Offset Pagination Linking
string offsetLinkHeader = Rfc8288LinkHeaderBuilder.Build(
    metadata: pagedResult.Metadata,
    pageUriFactory: page => $"https://api.example.com/items?pageNumber={page}&pageSize=20");

// Keyset Pagination Linking
string keysetLinkHeader = Rfc8288LinkHeaderBuilder.Build(
    metadata: cursorResult.Metadata,
    cursorUriFactory: (cursor, direction) => 
        $"https://api.example.com/items?cursor={cursor.Value}&direction={direction}");

// Set to response
httpContext.Response.Headers.Link = offsetLinkHeader;

5. Standalone ETag Generation & Verification

using Wiaoj.Pagination.AspNetCore.Caching;

// 1. Generate ETag from response bytes
byte[] utf8Payload = "{\"items\":[...]}"u8.ToArray();
string etag = ETagGenerator.GenerateWeakETag(utf8Payload); // W/"3fa85f64ac28d019"

// 2. Revalidate a read response; this is not a mutation precondition check.
string method = httpContext.Request.Method;
string? ifNoneMatch = httpContext.Request.Headers.IfNoneMatch;
if ((HttpMethods.IsGet(method) || HttpMethods.IsHead(method))
    && ETagGenerator.IsNotModified(ifNoneMatch, etag))
{
    // Return 304 Not Modified
    return Results.StatusCode(StatusCodes.Status304NotModified);
}

HTTP Response Headers Output

When calling an endpoint configured with .WithPagination(), the response includes:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
ETag: W/"5f8a92cb14e03d7a"
Link: <https://api.example.com/items?pageNumber=1&pageSize=20>; rel="first", <https://api.example.com/items?pageNumber=1&pageSize=20>; rel="prev", <https://api.example.com/items?pageNumber=3&pageSize=20>; rel="next", <https://api.example.com/items?pageNumber=5&pageSize=20>; rel="last"

{
  "items": [...],
  "metadata": {
    "totalCount": 100,
    "pageNumber": 2,
    "pageSize": 20,
    "totalPages": 5,
    "hasPrevious": true,
    "hasNext": true
  }
}

When a subsequent request is sent with If-None-Match: W/"5f8a92cb14e03d7a", the server returns:

HTTP/1.1 304 Not Modified
ETag: W/"5f8a92cb14e03d7a"

License

This project is licensed under the MIT License.

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 (1)

Showing the top 1 NuGet packages that depend on Wiaoj.Pagination.AspNetCore:

Package Downloads
Wiaoj.Pagination.OpenApi

OpenAPI integration for Wiaoj pagination contracts.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.5.3-alpha 0 12/6/2026
0.5.2-alpha 0 12/6/2026
0.5.1-alpha 0 12/6/2026
0.5.0-alpha.1 0 12/5/2026
0.4.2-alpha.2 58 12/3/2026
0.4.2-alpha.1 59 12/2/2026
0.4.1-alpha.3 65 11/30/2026
0.4.1-alpha.2 73 11/29/2026
0.4.1-alpha.1 77 11/28/2026
0.4.0-alpha.5 82 11/27/2026
0.4.0-alpha.4 70 11/15/2026
0.4.0-alpha.3 102 11/4/2026
0.4.0-alpha.1 74 10/30/2026
0.3.0-alpha.1 2,787 10/5/2026
0.2.0-alpha.3 80 9/24/2026
0.2.0-alpha.2 77 9/24/2026
0.2.0-alpha.1 78 9/24/2026
0.1.0-alpha.9 262 9/21/2026
0.1.0-alpha.8 73 9/21/2026
0.1.0-alpha.7 81 9/18/2026
Loading failed