Wiaoj.Http
0.5.1-alpha
dotnet add package Wiaoj.Http --version 0.5.1-alpha
NuGet\Install-Package Wiaoj.Http -Version 0.5.1-alpha
<PackageReference Include="Wiaoj.Http" Version="0.5.1-alpha" />
<PackageVersion Include="Wiaoj.Http" Version="0.5.1-alpha" />
<PackageReference Include="Wiaoj.Http" />
paket add Wiaoj.Http --version 0.5.1-alpha
#r "nuget: Wiaoj.Http, 0.5.1-alpha"
#:package Wiaoj.Http@0.5.1-alpha
#addin nuget:?package=Wiaoj.Http&version=0.5.1-alpha&prerelease
#tool nuget:?package=Wiaoj.Http&version=0.5.1-alpha&prerelease
Wiaoj.Http
Typed HTTP values, parsers, formatters, and conditional-request evaluation for .NET 11. Use it to work with validators, cache metadata, language preferences, links, query parameters, and URI references without taking a dependency on ASP.NET Core.
HTTP package guide · ASP.NET Core adapter
Using this source revision
This project targets net11.0 and is included in the libraries release train. For local
development against this source revision, reference the project or use a package built
from the same revision.
using Wiaoj.Http;
var query = HttpQuery.Empty.Append("tag", "http").Append("tag", "caching");
var tag = EntityTag.Strong("catalog-42");
var requestHeaders = new RequestPreconditions { IfNoneMatch = "W/\"catalog-42\"" };
var facts = new PreconditionFacts(PreconditionMethod.GetOrHead, true, new RepresentationValidators(tag));
var status = PreconditionEvaluator.TryEvaluate(
requestHeaders, facts, PreconditionEvaluationOptions.Default, out var decision);
// Success, NotModified (If-None-Match uses weak comparison).
API map · Query and typed header creation · Readers and URI references · Protocol semantics and limits · Verification
Wiaoj dependencies
Wiaoj.Primitives:ValueBuffer<char>for stack-first/pooled output,ValueList<T>for temporary lists.Wiaoj.Preconditions: argument guards. Both references use the existing centrally pinned Wiaoj version.
Delimiter scanning uses the built-in span Split enumerator. Production code does not opt into
experimental Primitives APIs. The historical splitter comparison keeps independent, fixed snapshots.
Shared wire grammar and cache directive names are internal implementation details. Owner-specific quality/weak-tag prefixes, date layouts and buffer thresholds stay private. The existing public Link relation constants remain available. The ASP.NET Core adapter uses framework header/status constants and the typed core cache policy; the core has no ASP.NET Core dependency.
APIs
| API | Purpose |
|---|---|
| LanguageTag | Supported BCP 47 subset, case normalization, span parsing and default-safe values |
| AcceptLanguageHeader | Stable quality ordering with span scanning and pooled overflow storage |
| LanguageMatcher | Prefix fallback with array/list scanning and alternate HashSet/FrozenSet span lookup |
| LanguageCatalog | Immutable FrozenDictionary prepared once; lookup of a parsed tag allocates no managed memory |
| EntityTag | Strong/weak comparisons, materialized lists, allocation-free raw condition scanning and TryFormat |
| CacheControl | Invariant formatting into stack storage; negative durations/invalid visibility rejected in constructor/init |
| VaryList | Immutable fields, bulk merge, cached rendering and field-token validation |
| LinkHeader | Validated URI/relation formatting; paging output written directly to final-size storage |
| QueryCanonical | Escaped query representation with explicit case, duplicate order and null policies |
| HttpQuality | Exact HTTP weights in thousandths, with checked double/decimal/Percentage conversion |
| AcceptLanguagePreference / AcceptLanguageValue | Validated preferences, stable quality order, retained duplicates and exclusions |
| EntityTagCondition | Explicit wildcard or ordered tag list, preserving strength and quoted commas |
| RequestPreconditionSet | Immutable typed construction of the four request preconditions; raw-reader interop |
| LinkValue / LinkHeaderValue | Validated immutable links, ordered relations and prepared header output |
| HttpRequestHeadersExtensions | Typed client request header replacement |
Query and typed header creation
Ordinary query construction uses HttpQuery, independently of sorted QueryCanonical output:
HttpQuery.Empty.Append("tag", "a").Append("tag", "b").Set("page", "2") produces
tag=a&tag=b&page=2. Null values are key-only; empty strings retain =. Set replaces all matching
keys at their first position, SetValues preserves supplied value order, and Remove removes all matches.
Lookup is ordinal by default; WithComparison explicitly selects ordinal-ignore-case matching.
The immutable result copies input pairs and retains limits through edits. FromPairs stops enumeration
at configured limits. Limits bound encoded output and pair count; parsing additionally checks raw input.
ParseEncoded accepts query text without ?, strictly decodes percent-encoded UTF-8 and treats +
as a literal plus, never a form-space. Output uses uppercase RFC 3986 percent escapes and may normalize
equivalent input spelling. Raw component constructors encode % as data. Malformed Unicode/escapes
are rejected. Empty encoded text means zero pairs; an explicitly constructed empty key-only pair also
has empty wire output, so its pair count cannot round-trip through empty text. Empty segments in a
nonempty input, including trailing separators, remain pairs and consume limits. Prepared TryFormat
has the same no-partial-write contract as the header formatters; construction/edits own allocated arrays
and strings. General URI composition is a separate layer.
var weight = HttpQuality.FromPercentage(Wiaoj.Primitives.Percentage.Half);
var languages = AcceptLanguageValue.Create(
new AcceptLanguagePreference(LanguageTag.Parse("tr-TR")),
new AcceptLanguagePreference(LanguageTag.Parse("en"), weight),
AcceptLanguagePreference.Wildcard(HttpQuality.Zero));
// tr-TR, en;q=0.5, *;q=0
var conditions = RequestPreconditionSet.Empty
.WithIfNoneMatch(EntityTagCondition.Of(EntityTag.Weak("revision-1")))
.WithIfModifiedSince(DateTimeOffset.UtcNow);
using var request = new HttpRequestMessage(HttpMethod.Get, "https://example.com/items");
request.Headers.SetAcceptLanguage(languages);
request.Headers.SetPreconditions(conditions);
HttpQuality stores integer thousandths (0 through 1000). FromDouble, FromDecimal and
FromPercentage reject values requiring rounding; use integer thousandths for calculated weights.
Percentage remains a general floating-point ratio, while the HTTP type enforces at most three
fractional digits. Default quality is zero. Output omits q=1 and trims trailing fractional zeros.
Accept-Language output sorts by descending quality with stable ties; duplicates and q=0 remain.
All 1001 weights are covered by round-trip and buffer regressions. The tolerant existing reader is unchanged.
Header collections copy their inputs and reject empty lists/default entries. EntityTagCondition.Any
is a wildcard with zero listed tags; it is distinct from EntityTagCondition.Of(EntityTag.Strong("*")).
Tag lists and links preserve input order and duplicates. Optional HttpInputLimits configuration is
provided through explicit overloads; construction checks the canonical output's character and item counts.
RequestPreconditionSet is an immutable value: With methods replace one field, Without methods
remove it, and default/Empty has no fields. Dates serialize in UTC IMF-fixdate, dropping fractional
seconds. Construction does not decide whether a resource exists or which representation is selected.
ToRaw() returns RequestPreconditions; the raw reader model still represents absent, present-empty
and malformed fields. Typed values implement IPreconditionHeaders for direct generic evaluation.
TryFormat writes into caller-owned character storage: insufficient capacity returns false with
zero characters written and leaves the entire destination unchanged. Default EntityTag, LinkValue
and AcceptLanguagePreference cannot be serialized: their TryFormat returns false; ToString and
GetFormattedLength throw. Invalid raw arguments to LinkHeader throw before any write.
Default CacheControl and VaryList.Empty have valid empty output. All formatters are culture independent.
LinkHeader.TryFormatPaging writes zero characters successfully if no links are supplied.
Prepared language, condition and link collections cache their final strings. Reusing those values avoids repeated materialization; constructing them allocates their owned storage. CacheControl/EntityTag/LinkValue string output allocates the result. Caller-buffer formatters allocate zero managed memory after warmup. There is no shared formatting interface: concrete span methods avoid boxing value types and do not force parse/provider/format members on types whose wire format is fixed.
Client Set methods replace the named value. SetPreconditions replaces all four fields and removes fields absent from the supplied set. Null/default-invalid inputs are rejected before mutation. The client adapter uses validated output with TryAddWithoutValidation; it is not a raw header-writing API. The BCL may normalize whitespace when its typed header properties parse a value.
Readers and URI references
The canonical package source and HTTP tests now live in wiaoj/libraries under src/Http and tests/Http. Both HTTP projects target net11.0 and are included in the libraries release train. The established minimum Primitives/Preconditions dependency remains 0.4.0-alpha.3.
For repeated URI generation, FormatWithQueryParameters writes query replacements directly into the final URI string; TryFormatWithQueryParameters writes into caller storage. These preserve Set ordering, duplicate removal, fragment placement and limits without allocating edited query/reference objects. Replacement names must be unique under query comparison. Up to eight replacements use linear lookup and stack storage; larger sets use a dictionary and pooled seen flags. Small prepared buffer paths have zero-allocation regressions. Empty replacement sets preserve the original encoded spelling.
HttpResponseHeaders.ReadEntityTag/ReadCacheControl/ReadVary/ReadLinks use raw NonValidated header lines. HttpHeaderReadResult distinguishes absence (IsPresent=false) from present-empty fields and Invalid, Unsupported or LimitExceeded results. Value is available only on HasValue; TryGetValue returns false otherwise. Empty Cache-Control/Vary/Link lists remain present-empty; empty or repeated ETag is Invalid. Strict/tolerant ETag and Link policy is explicit through overloads; all readers have explicit limits. These four fields belong to HttpResponseHeaders; no irrelevant HttpContentHeaders API is added.
CacheControlReadResult retains directive order, unknown extensions and quoted values. TryGetPolicy only
projects the whole value when every directive fits CacheControl. Field-qualified private/no-cache, unknown
extensions and durations exceeding Int32 are Unsupported for projection, not silently dropped. Malformed
numeric values, duplicate supported directives and public/private conflicts are Invalid. Canonical output emits max-age, s-maxage, stale-while-revalidate and stale-if-error as unquoted decimal digits, even if the input quoted them. Constructing a max-age or s-maxage directive with a missing or non-digit value throws. Other valued directives supported by the reader retain their quoted canonical formatting. Unknown extensions are retained; original whitespace, casing, and quoting are not guaranteed. See RFC 9111 §5.2.
Read limits bound raw characters/items across lines before materialization; parsing never joins lines first.
Reader materialization allocates owned models/strings; prepared result TryFormat does not allocate.
LinkHeaderReader.TryParse/TryParseLines reads protected target/quoted syntax and returns ordered HttpLink
values. Strict failures return no partial links; tolerant mode skips entire invalid/unsupported items and
reports counts. Unbalanced tails consume the rest of their line, avoiding speculative resynchronization.
Limits count raw characters and comma-delimited items, including empty items, across all lines.
Unknown ordinary parameters and repeated hreflang values are retained. RFC singleton parameters keep
the first occurrence; IgnoredParameters reports discarded duplicates. Canonical formatting quotes and
escapes values; it preserves semantics, not original whitespace/quoting. HttpLink construction rejects
duplicate singletons and requires rel. Relations may be space-separated; registered comparisons ignore
case, extension URI comparisons are ordinal. Empty targets are valid relative URI references here.
LinkParameter supplies typed rel/anchor/title/type/hreflang creation alongside validated ordinary extension parameters. The supported value subset is printable ASCII; extended parameters such as title* and quoted HTAB/obs-text return Unsupported rather than being silently discarded or misinterpreted. Header injection controls are Invalid. Legacy LinkValue/LinkHeaderValue behavior remains unchanged. New HttpLink values can be written with the adapter's SetLink/AppendLink overloads.
Resolve requires the representation URI and returns both Target and Context; anchor changes Context and must not be ignored when applying a link. Target and anchor are independently resolved against the representation URI, not a base supplied by the document body. Parsing itself never follows a link.
HttpUriReference composes URI references without application routing/origin policy. FromPath encodes
a raw complete path while retaining slash boundaries; FromPathSegments encodes each segment's slashes
as data. Dot segments remain until explicit ResolveAgainst(System.Uri) resolution. Raw paths beginning
// are rejected to avoid accidentally creating an authority; explicit ParseEncoded accepts network-path
and absolute references. Generic URI schemes are supported, not an application redirect allow-list.
ParseEncoded requires ASCII URI syntax and valid percent triplets; query components additionally require
valid UTF-8. Parsing preserves wire spelling, including query escapes and bare ?/#. Query edits normalize
only the query via HttpQuery, preserve fragment placement and repeated pair order, and never sort keys.
WithQuery(Empty) retains ?; WithoutQuery removes it. Removing the last parameter retains a present-empty
query. WithFragment accepts raw data; WithoutFragment removes it. Limits cover complete output and query
item counts and remain attached to the reference. TryFormat has the same all-or-nothing buffer contract.
Parsing, formatting and RFC comparison remain static, deterministic operations with explicit inputs. They do not own request state, mutable global configuration or disposable resources. Immutable prepared values can be reused across requests. Evaluation receives its clock and limits through explicit PreconditionEvaluationOptions, including TimeProvider for deterministic date tests.
Application-specific tenant policy, configuration reload, external revision lookup and resource selection belong in application services. Such a service may call these static functions; wrapping every formatter in a DI interface would add registration and lifetime obligations without adding a substitution point. Keep Primitives/Preconditions below Http, and pagination decisions above it; Http must not depend on application code, pagination metadata or ASP.NET Core. See also the adapter's extension/lifecycle guidance.
using Wiaoj.Http;
var languages = new LanguageCatalog(["tr", "en", "zh-Hant"]); // construct once
var requested = LanguageTag.Parse("tr-TR");
languages.TryLookup(requested, out string selected);
var tag = EntityTag.Strong("revision-1");
bool unchanged = EntityTag.MatchesAnyCondition("W/\"revision-1\"", tag);
Only final public results are materialized; temporary buffers are disposed before returning. Small inputs use bounded stack storage, and larger inputs use Wiaoj-managed pooled overflow. There is no global cache of request-controlled keys. Small Vary lists use linear comparisons; stable language catalogs use frozen indexes instead of rebuilding dictionaries per request.
Protocol semantics and limits
Query separators, spaces and Unicode are percent-encoded, preventing ambiguous key/value boundaries.
The default query policy preserves key case and repeated-value order; null values encode as empty.
Use QueryCanonicalOptions.CaseInsensitiveSorted for a lowercase, sorted contract, or configure LowercaseKeys, SortValues and NullValues independently.
KeyOnly distinguishes null from empty; Omit omits null pairs. ASP.NET Core's parsed query collection
already groups names case-insensitively, so the adapter cannot recover spelling/order discarded upstream.
NaN quality weights, invalid Vary tokens, unsafe Link relation text and non-byte-range ETag characters
are rejected. Default entity tags do not match as validators. CacheControl validates constructor and
with/init values immediately and preserves deconstruction. Null tag factory arguments fail as argument errors.
AcceptLanguageHeader.Parse retains q=0. Lookup excludes a candidate according to its most specific
basic range; zero wins duplicate ties. Explicit positive child ranges override broader exclusions for
that child, but cannot re-enable an excluded parent through fallback. If an existing candidate is excluded, TryLookupBest continues to the next ancestor before moving to a different range. TryLookupBest skips wildcard
ranges, following the package's lookup policy. TryNegotiate accepts an explicit default and rejects
it when excluded. Whether to return 406 or serve a configured default when no language is acceptable is application policy.
The language parser retains its 35-character limit and restricted tag forms. Lookup is syntactic,
without likely-subtag data; duplicate quality and unknown-parameter tolerance remain.
PreconditionEvaluator.TryEvaluate returns a parse status and reports Continue, NotModified or PreconditionFailed using RFC 9110
section 13.2.2 ordering. It handles strong If-Match, weak If-None-Match, date precedence, second precision,
three HTTP-date forms and explicit representation existence. Invoke it after ordinary request checks.
Range/If-Range, historical validator metadata, and detecting an already-applied write are outside its scope.
Breaking migration: the previous PreconditionEvaluator.Evaluate and TryEvaluate overload families
are replaced by the single generic TryEvaluate above. Both values and repeated-line transport views
implement IPreconditionHeaders. Pass existence, method classification and validators as
PreconditionFacts and explicitly handle LimitExceeded (no partial result). Use Query for a
read-only HTTP QUERY; matching If-None-Match is still 412, not 304. Use Other for other methods;
write preconditions must run before changing state.
EntityTag now accepts empty opaque tags, distinct from default(EntityTag). Strict parsing accepts the
case-sensitive W/ marker and HTTP OWS (SP/HTAB); use HttpParseMode.Tolerant explicitly for lowercase w/.
Default tags cannot be formatted: TryFormat returns false and ToString throws. The 128-character opaque
limit remains a package restriction. List parsers still skip malformed elements.
The RFC850 fifty-year cutoff compares complete timestamps via an optional TimeProvider, including leap-day validation.
Pass HttpInputLimits to AcceptLanguage parsing, entity-tag list parsing or query canonicalization
to bound characters and raw item counts. Limits are opt-in; configure transport byte/header limits too.
Query limits count decoded key/value characters before escaping, and count omitted null pairs as work.
TryParse, TryParseList, TryBuild and PreconditionEvaluator.TryEvaluate return HttpParseStatus.LimitExceeded
without throwing for excess input. Parse and Build remain throwing convenience wrappers. Configuration
errors (null arguments, invalid enum values) still throw. Precondition limits aggregate all supplied lines
before any match can short-circuit. Implement IPreconditionHeaders for a custom transport's header view;
the generic evaluator carries struct implementations without boxing.
Query canonicalization retains the measured small-input BCL path for known collections up to eight pairs. Larger escaped queries use a pooled encoded arena, native struct comparer and string.Create to avoid per-pair escaped strings. Arrays are returned with clearing. Accept-Language sorting also uses a native struct comparer. LanguageCatalog pre-sizes its construction dictionary when the input count is known.
The Subtags compatibility property materializes an immutable array on demand. For hot lookup paths,
reuse LanguageCatalog/LanguageMatcher rather than enumerating Subtags or materializing fallback tags.
Verification
dotnet test --project tests/Http/Wiaoj.Http.Tests.Unit/Wiaoj.Http.Tests.Unit.csproj -c Release
See the unit test guide and HTTP benchmark guide for scope and methodology. Build the sources with the .NET 11 SDK.
Explicit overloads
Optional parameters are not used in this package. Configuration overloads accept non-null options and limits; omission selects a dedicated overload with a reusable default. Passing null configuration throws. CancellationToken = default is the only permitted exception, enforced by assembly-wide tests.
var request = new RequestPreconditions { IfNoneMatch = header };
var validators = new RepresentationValidators(tag, modified);
var evaluation = new PreconditionEvaluationOptions { TimeProvider = clock, Limits = limits };
var facts = new PreconditionFacts(PreconditionMethod.GetOrHead, true, validators);
var status = PreconditionEvaluator.TryEvaluate(request, facts, evaluation, out var result);
var cache = CacheControl.Public(60) with { StaleIfError = 300 };
var customCache = new CacheControl { MaxAge = 60, MustRevalidate = true };
RequestPreconditions and CacheControl retain explicit full constructors and deconstruction; partial configuration uses validated init properties. Common evaluator overloads accept no validators, an ETag, a date, or both. Advanced settings are grouped in PreconditionEvaluationOptions. Reuse that options instance on allocation-sensitive paths. EntityTag parsing has explicit strict/mode/limits overloads; query construction has separate default/options/limits/full overloads. HttpInputLimits.Unlimited names the unrestricted default rather than using null as configuration. Nullable header/validator data still expresses genuinely missing HTTP metadata.
For uncertain encoded query input, use HttpQuery.ReadEncoded. Match its C# 15 union as HttpQuery, InvalidQueryEncoding, or QueryLimitExceeded. ParseEncoded remains the throwing convenience for known valid input.
Retry-After
Use RetryAfter.GetDelay(response.Headers, clock) to interpret the typed HTTP
header. Delta-seconds of zero is a real hint; missing, malformed, out-of-range
headers and HTTP dates at or before now have no usable hint. An HTTP-date is
interpreted against the supplied provider's UTC clock.
If you must account for time spent processing the response before consuming
the hint, use RetryAfter.Capture(response.Headers, clock) and then
countdown.GetRemainingDelay(). The countdown uses the same provider's
monotonic timestamp and won't grow or expire early when UTC jumps. It is
process-local; don't store it in a job, database or message.
The helper doesn't sleep, choose eligible responses, add jitter, cap a
consumer's wait budget or schedule a retry. For writing a relative field,
RetryAfter.ToDeltaSeconds(delay) rounds up to whole seconds and caps the
result to the platform typed header's nonnegative 32-bit range.
Authentication challenge fields
Use the platform's AuthenticationHeaderValue for a single scheme and opaque credentials.
When reading multiple WWW-Authenticate field values or editing named challenge parameters,
AuthenticationChallenges preserves each scheme's boundaries, credential form, and
parameter order. Pass the response's raw/non-validated field values to avoid any
normalization before calling TryParse. Unlike token68, named values may be quoted and
can include escaped quote or backslash characters.
TryAddParameter adds a quoted value to matching parameter-capable challenges and
matches names exactly, ignoring case. Other field text remains unchanged; a malformed
list is not repaired, and token68 credentials are not changed into named parameters.
Repeated names are recognizable by readers and left untouched by the editor. The helper
does not validate credentials, choose a scheme, or interpret application parameters.
See RFC 9110 §11.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Wiaoj.Preconditions (>= 0.4.0-alpha.3)
- Wiaoj.Primitives (>= 0.4.0-alpha.3)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on Wiaoj.Http:
| Package | Downloads |
|---|---|
|
Wiaoj.WellKnown.Discovery
Client discovery for well-known OAuth and authorization server metadata. |
|
|
Wiaoj.Http.AspNetCore
ASP.NET Core adapters for Wiaoj.Http: conditional GET, Vary header merging and query canonicalization. |
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 |