Wiaoj.Http.AspNetCore 0.5.1-alpha

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

Wiaoj.Http.AspNetCore

Adapters for ASP.NET Core 11. Use Wiaoj.Http for protocol semantics and this package for HttpContext, header and query integration. It references Microsoft.AspNetCore.App and adds no serialization, resilience, database, or result-model dependency.

Package and framework

This package targets net11.0 and is included in the libraries release train. It requires ASP.NET Core and depends on the Wiaoj.Http core package. Pagination.AspNetCore uses its ReadDecodedQuery() adapter so that paging links preserve decoded repeated query values before re-encoding the URL.

Choose an entry point

API Purpose
HttpContext.TryHandleConditionalGetOrHead Recommended for an existing, selected GET/HEAD representation; applies one cache policy to the final 200 and to 304
HttpRequest.TryNegotiateLanguage Select a supported language without changing culture, status, or headers
ConditionalRequest.TryHandle Explicit existence, wildcard, GET/HEAD and write preconditions (304/412)
ConditionalGetPolicy Immutable preformatted headers reusable across requests for the same representation
IHeaderDictionary.AppendVary Merge missing fields, with an allocation-free already-present fast path
IQueryCollection.ToCanonicalQuery Flatten values without per-key LINQ closures and use escaped core normalization
IHeaderDictionary.SetEntityTag / SetCacheControl / SetVary / SetLink Replace response fields using validated core values
IHeaderDictionary.AppendVary(VaryList) / AppendLink Merge Vary fields or append validated Link values explicitly
IHeaderDictionary.SetAcceptLanguage / SetIfMatch / SetIfNoneMatch Typed request-header writing, useful in adapters and tests
IHeaderDictionary.SetPreconditions / ReadPreconditions Replace all four preconditions or snapshot raw header lines

Quick start: conditional GET with a selected representation

For a runnable example with separate English and Turkish representations, see the standalone ASP.NET Core sample.

This example exposes a fixed public representation. In an application, resolve authorization, existence, and the relevant representation first; use the selected representation's validators and cache policy, not client input.

using Wiaoj.Http;
using Wiaoj.Http.AspNetCore;

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

var tag = EntityTag.Strong("greeting-v1");
var cache = CacheControl.Public(60);
var policy = new ConditionalGetPolicy(tag, cache);

app.MapGet("/greeting", (HttpContext context) =>
{
    if (context.TryHandleConditionalGetOrHead(policy))
        return Results.Empty; // The helper already set the response status.

    return Results.Text("Hello");
});

app.Run();
Outcome Handler responsibility
Return false Continue the ordinary response. Write the normal representation. The quick-start helper applies the selected cache policy if the final response is 200.
Return true Stop writing the normal response. Depending on the inputs, the helper already selected 304, 412, or 431.
Ordinary routing, authorization, or validation failure Preserve the normal outcome; do not turn a 401, 403, or read-time 404 into 304. Let the application establish that outcome before calling the helper.

The read helper is for GET/HEAD only, before the response starts. It takes the policy from the caller; it does not choose a cache lifetime or make a response public. Pass explicit PreconditionEvaluationOptions to bound parser work or use a custom clock. The default does not add a parser budget, so keep transport limits in place. For missing resources or a Last-Modified validator, use the detailed API below.

For a conditional write, evaluate before mutation. The application's persistence boundary must enforce the same revision atomically; an HTTP helper alone cannot prevent a concurrent update after the check.

Extension surface and lifecycle

IHeaderDictionary also provides ReadEntityTag/ReadCacheControl/ReadVary/ReadLinks with the same core result and limit contracts as HttpResponseHeaders. Presence and repeated lines remain distinct; a present empty StringValues is not turned into absence. Extended HttpLink values with attributes can be written using SetLink/AppendLink. All reader adapters are stateless; failed or unsupported input never yields a partial cache policy. Their materialized output allocations are separate from prepared buffer formatting.

HttpRequest.GetRelativeUriReference includes PathBase, Path and the raw QueryString without using Host or forwarded headers. It preserves encoded wire spelling; its query view follows RFC URI plus semantics. For ASP.NET form-decoded values use IQueryCollection.ReadDecodedQuery: it retains each StringValues element, encodes decoded names/values once, and uses ordinal-ignore-case key lookup. Empty StringValues maps to a key-only pair. Both adapters accept explicit limits; neither performs canonical sorting or route selection.

These are transport adapters, so they remain static extension methods. They do not capture a context, resolve services, own a clock or require AddWiaojHttp registration. There is no mutable global policy. ConditionalRequest/ConditionalGet also remain static: selected validators, existence, policy and optional configuration are explicit arguments through overloads. A prepared ConditionalGetPolicy is an immutable instance, reusable across requests for the same selected representation.

Use application services for tenant-specific policy, dynamic options and external validator lookup. The handler establishes authorization, existence and representation selection before evaluation. An automatic middleware/filter cannot infer those decisions safely; no universal caching middleware, service-locator extension or generic unvalidated header bag is introduced. Existing query canonicalization is for canonical output, not a general URI/query builder.

var links = LinkHeaderValue.Create(new LinkValue("/items?page=2", LinkHeader.RelNext));
response.Headers.SetLink(links);
response.Headers.SetCacheControl(CacheControl.Public(60));
response.Headers.AppendVary(VaryList.Of("Accept-Language", "Accept-Encoding"));

// A transport view preserving repeated lines and present-empty fields:
var incoming = request.Headers.ReadPreconditions();
var status = PreconditionEvaluator.TryEvaluate(incoming, facts, evaluationOptions, out var decision);

Set methods replace existing values. Empty VaryList and empty CacheControl remove the corresponding field. SetPreconditions replaces all four fields, removing any fields absent from the typed set; use SetIfMatch/SetIfNoneMatch to change only one. AppendVary merges case-insensitively, preserving an already sufficient header; AppendLink appends a separate line and retains existing links. Header values are validated completely before mutation. This is not a transaction against concurrent access or a custom IHeaderDictionary throwing during writes; request/response headers must be owned by the current operation.

ReadPreconditions returns AspNetPreconditionHeaders, preserving each line without concatenation or allocating a list. It retains field presence separately from the value count. Do not mutate arrays backing StringValues while evaluating the view. Combining lines into one raw string would lose invalid-but-present input distinctions and could change tolerant wildcard evaluation. Default view has no headers.

There is no implicit cache policy in the writers. SetEntityTag and SetCacheControl materialize their strings; prepared ConditionalGetPolicy paths reuse cached wire values. Prepared language/link/condition writing, already-present Vary merging and the raw header view have warmed zero-allocation regressions. Caller-buffer formatting is supplied by the core; IHeaderDictionary itself accepts strings/StringValues.

Real Kestrel tests cover typed client writing to server parsing and typed response writing to client reading for HTTP/1.1 and HTTP/2, including GET/HEAD, 304/412, Vary merging and no-store on 412. The existing compression matrix retains weak shared validators and encoding-specific strong validators under gzip, Brotli and Zstandard. No package can establish application resource existence automatically.

using Wiaoj.Http;
using Wiaoj.Http.AspNetCore;

// Prepare once per stable representation; do not build an unbounded cache from arbitrary request keys.
var policy = new ConditionalGetPolicy(EntityTag.Strong("revision-1"),
    CacheControl.Public(60), "Accept-Language", "Accept-Encoding");

// In the handler, after establishing that this resource exists:
var selected = new ConditionalResponse(true) { Policy = policy, StampSuccessfulRead = true };
if (ConditionalRequest.TryHandle(context, selected, PreconditionEvaluationOptions.Default)) return;
// Write the normal representation; OnStarting stamps ETag, Cache-Control and Vary for a final 200.

Breaking migration: ConditionalGet and both TryHandle overloads are removed; migrate to ConditionalRequest.TryHandle and opt in to StampSuccessfulRead to retain final 200 GET/HEAD stamping. Policy Vary fields are merged on both 200 and 304 without replacing other fields. The previous raw cache-string facade now uses ConditionalGetPolicy to validate and prepare the headers.

AppendVary preserves an existing header when it already contains the requested fields. Otherwise it performs one bulk merge, validating added field tokens. Prepared-policy 304 responses reuse formatted strings; measured zero managed allocation applies to the warmed helper path, excluding context creation, HTTP transport, policy construction and initial header dictionary allocation.

Migration: import Wiaoj.Http.AspNetCore for adapters and replace QueryCanonical.Build(request.Query) with request.Query.ToCanonicalQuery(). Both projects in this source revision target .NET 11.

dotnet test --project tests/Http/Wiaoj.Http.AspNetCore.Tests.Unit/Wiaoj.Http.AspNetCore.Tests.Unit.csproj -c Release
dotnet test --project tests/Http/Wiaoj.Http.AspNetCore.Tests.Integration/Wiaoj.Http.AspNetCore.Tests.Integration.csproj -c Release

Integration tests use in-memory TestServer, including actual OnStarting execution, encoded query input, method/status handling and 50 batches of 8 parallel requests for each prepared-policy response path. Additional loopback Kestrel tests exercise HTTP/1.1 and cleartext HTTP/2, gzip/Brotli/Zstandard revalidation, encoding-specific strong validators, HEAD, client cancellation, transport header limits and parser limits. These do not establish proxy or distributed-system behavior.

Use the single ConditionalRequest.TryHandle(context, selected, options) after routing, authorization and representation selection, before any mutation. Stop writing when it returns true. Supply existence, optional policy and Last-Modified in ConditionalResponse. It writes 304/412 metadata immediately; 412 responses use no-store. A Continue result leaves success headers to the caller unless final GET/HEAD 200 stamping is enabled. Options set the aggregate header limits (431 on excess) and obsolete-date clock, and must be non-null. Header lines are scanned directly without concatenation. QUERY keeps its own method classification; matching If-None-Match returns 412.

Select strong ETags per encoded representation, or use a shared weak tag for semantically equivalent identity/gzip/Brotli/Zstandard variants. Always include Accept-Encoding in Vary when encoding varies. When a read-only endpoint filter evaluates conditionals after a successful handler result, it can preserve 404/400 responses even with wildcard conditions. The handler still runs before a 304; serialization and response-body transmission are skipped.

Query: choose by input and intent

For ?tag=red&tag=blue&q=a+b, choose one path rather than feeding an already decoded value back into a parser:

Intent Use Meaning of the example
Edit decoded values in an ASP.NET Core request request.ReadDecodedQuery() Keeps both tag values. ASP.NET Core has already decoded q as a b.
Read an encoded URI query with URI-component semantics HttpQuery.ReadEncoded("tag=red&tag=blue&q=a+b") Pass the query component without the leading ?. Keeps both tag values; the literal plus in a+b is not a space. Match the result to distinguish invalid encoding from a limit violation.
Produce a specified canonical string from decoded values request.Query.ToCanonicalQuery(options) Use only when your protocol specifies normalization. It is not a raw-wire round trip; the decoded space is encoded as %20.

Canonicalization defaults preserve key case and order within repeated values. Select QueryCanonicalOptions.CaseInsensitiveSorted only when the consuming protocol expects it. TryToCanonicalQuery reports a limit failure without throwing.

Language negotiation

string[] supportedLanguages = ["en", "tr"];
if (context.Request.TryNegotiateLanguage(supportedLanguages, "en", out var language))
{
    // Use language for representation selection before evaluating cache preconditions.
}

The fallback is supplied by the application and cannot override a q=0 exclusion. The helper does not set culture, Content-Language, Vary, or a response status. If the representation varies by language, include Accept-Language in its cache policy. Use request.NegotiateLanguage with explicit HttpInputLimits when you need to distinguish LimitExceeded from a successful parse with no acceptable language (null).

Explicit overloads

No method or constructor has optional parameters. CancellationToken = default is the only allowed exception, guarded by assembly-wide tests. Supply a policy and date in the selected response; pass evaluation settings explicitly. Reuse prepared options and policies.

var selected = new ConditionalResponse(exists) { Policy = policy, LastModified = modified };
var options = new PreconditionEvaluationOptions { Limits = limits, TimeProvider = clock };
ConditionalRequest.TryHandle(context, selected, options);
request.Query.ToCanonicalQuery();
request.Query.ToCanonicalQuery(QueryCanonicalOptions.CaseInsensitiveSorted);
request.Query.ToCanonicalQuery(QueryCanonicalOptions.CaseInsensitiveSorted, limits);

When passing target-typed new to an overloaded configuration position, use the explicit type or a typed local to distinguish policy/options/limits. Empty queries validate configuration without allocating an iterator.

Migration and query input

  • Replace context.TryHandleConditionalRead(policy) with context.TryHandleConditionalGetOrHead(policy). A true result means the response was handled and the endpoint must not write its normal body.
  • Replace request.Query.ReadQuery() with request.ReadDecodedQuery(). Pass explicit HttpInputLimits at an untrusted boundary. If you already have the collection, use query.ReadDecodedQuery(limits).
  • Use request.ReadRawQuery(limits) for the encoded query, with URI-component semantics. On ?q=a+b&flag&empty=, the raw read has a literal plus, a key-only flag, and an empty value. With ASP.NET's decoded form, the plus becomes a space and a key-only flag may normalize to an empty value. Use canonical sorting only when the consuming protocol calls for it.
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.Http.AspNetCore:

Package Downloads
Wiaoj.Pagination.AspNetCore

ASP.NET Core integration for Wiaoj pagination.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.5.1-alpha 0 12/6/2026
0.5.0-alpha.1 0 12/5/2026