Dangl.RestClient
Changelog
Online Documentation
This project provides DanglHttpClient to easily interact with all Dangl web services.
To avoid TCP exhaustion, HttpClients and derived types should always be used as singletons.
ITokenHandler
The ITokenHandler is an interface that be be used to support the automatic
obtaining of Tokens and refreshing them. It can be configured to support either of
the functionalities or none at all. If none is supplied, by default a NoOpTokenHandler
is used that does not perform any operations.
It can be used, for example, in server backends that use the ClientCredentials grant.
If you want to act when a token is obtained or refreshed, you can use the EventHandler<TokenUpdateEventArgs> TokenUpdate
event on the ITokenHandler.
ITokenStorage
The ITokenStorage is an interface that is used to store and persist tokens, e.g.
it could use the local app storage on a mobile app or the database in a server application.
It is used so that only tokens and not the full user credentials need to be stored.
By default, there's an InMemoryTokenStorage for non-persisting use available.
DanglHttpClientAccessor
This is a simple class that only keeps a reference to an HttpClient. When the HttpClientFactory pattern
is used, this class can be specified as a dependency to be able to have easy access via dependency injection to
a correctly lifetime-managed HttpClient.
JSON request helpers and cancellation
GetJsonAsync<TResponse>, PostJsonAsync<TResponse, TPayload> and PutJsonAsync<TResponse, TPayload> now
have overloads with a final CancellationToken parameter:
using var wrapper = await client.GetJsonAsync<MyResponse>(url, cancellationToken);
using var posted = await client.PostJsonAsync<MyResponse, MyPayload>(url, payload, cancellationToken);
using var updated = await client.PutJsonAsync<MyResponse, MyPayload>(url, payload, cancellationToken);
The token is passed to HttpClient.SendAsync, including its normal response-body buffering. Already-canceled
calls do not serialize a payload or send a request. Cancellation propagates as OperationCanceledException,
not as an ApiError. JSON helpers dispose their generated request/content on every exit path, including
success and transport failures. If response processing throws, they also dispose any received response.
A returned wrapper owns wrapper.Response: dispose the wrapper when finished. The managed HttpClient
is not disposed by these helpers.
Both ResponseWrapper.GetResponseWrapperAsync(response, cancellationToken) and
ResponseWrapper<T>.GetResponseWrapperAsync(response, cancellationToken) also accept a token. Ownership
of the supplied response transfers to the wrapper when the factory returns; if it throws, ownership stays
with the caller. All existing overloads remain available and delegate with CancellationToken.None.
Cancellation is cooperative: on netstandard2.0, standalone wrapper content reads and synchronous JSON
serialization/deserialization are checked at operation boundaries, rather than forcibly interrupted.
The existing token-handler and token-storage interfaces are unchanged and do not accept cancellation tokens.
Response ownership and error classification
Both wrapper types implement IDisposable. Disposing a wrapper disposes its response/content, but not the
response's request or the deserialized result. Requests created by JSON helpers have already been disposed
when those helpers return; their URI/headers remain available for diagnostics, but their content must not be reused.
ErrorKind distinguishes None, HttpError and InvalidResponseBody. HTTP errors retain their status and
structured ApiError details. Missing or malformed error details retain the compatible Unknown Error
fallback and expose DeserializationException. A malformed or unexpectedly empty successful JSON body
sets IsSuccess = false, ErrorKind = InvalidResponseBody, and exposes the JSON diagnostic. Explicit JSON
null remains a valid result for compatible types; successful 204, 205 and HEAD responses require no body
and return default(T).
Behavior change: content-read/transport failures, cancellation and unexpected non-JSON exceptions now
propagate instead of becoming Unknown Error. Only JSON deserialization failures are represented by wrapper
diagnostics. Use using for returned wrappers and handle exceptions separately from HTTP/API errors.
FallbackHandler
The FallbackHandler is a DelegatingHandler that can be configured with multiple baseUrls. If a request
is returning an error that can possibly be recovered from by pointing to a fallback, the request is sent again
to the next available fallback url.
Only GET and HEAD retry automatically, on HTTP 5xx responses or HttpRequestException. Cancellation and other
exceptions are propagated without retries. Discarded responses are disposed; the final response belongs to the caller.
Requests eligible for retries buffer their content once before sending and use a separate request/content instance
for each attempt. Buffering failures propagate before any request is sent; large streaming uploads should avoid retries.
To retry other methods, set FallbackHandler.RetryUnsafeMethods = true, or use
services.AddDanglHttpClient<MyClient>(retryUnsafeMethods: true, baseUrls: new[] { primaryUrl, fallbackUrl }).
The AddDanglHttpClient<TService, TImplementation> overload supports the same option. Only opt in when the
server guarantees repeating the operation is safe, for example through an idempotency key. This is a behavior
change: existing POST, PATCH, PUT and DELETE requests no longer automatically retry.
Fallback routing matches the request's scheme, host, effective port and case-sensitive path scope, using the
same rules as authentication below. Absolute URLs outside those scopes are sent unchanged without retries.
When scopes overlap, the most specific matching path is tried first. Retries preserve the endpoint path relative
to that scope and the query string: https://primary.example/api/values?sort=true can fall back to
https://backup.example/v2/values?sort=true when the configured bases are /api and /v2 respectively.
Relative paths without a leading slash resolve beneath the first configured base path, whether or not the
base ends in /. A leading slash retains standard URI semantics and resolves from the host root; paths
outside the configured scope are not retried.
AuthenticationHandler
The AuthenticationHandler internally uses ITokenHandler and ITokenStorage to append OAuth2 Bearer
authentication to whitelisted urls.
Allowed URLs must match the configured scheme, host and effective port, and use the exact configured path or
a descendant path. Hosts are case-insensitive and default ports are equivalent; paths are case-sensitive.
For example, a base of https://example.com/api allows /api and /api/values, but not /api2, /API/values,
https://example.com.evil.test/api, or a different scheme or port. A trailing slash on the base is optional;
request query strings do not affect matching. Requests with embedded credentials do not match.
Behavior change: both handlers and all AddDanglHttpClient overloads now require absolute HTTP(S) base URLs
without embedded credentials, query strings or fragments. Unsupported bases throw ArgumentException during
construction or registration rather than silently defining an ambiguous scope.
Automatic token acquisition and refresh share one in-flight operation per ITokenStorage instance, including
across different AuthenticationHandler instances and typed clients. Concurrent requests needing an update
receive the same returned token, null result or exception. Storage is rechecked before calling the token
provider; requests with sufficiently fresh tokens do not wait for an update. Different storage instances remain
independent, so separate users or credential contexts are not globally serialized. Share a storage instance
only when those clients intentionally share the same credentials. Completed results are not cached by the
coordinator; later requests can retry after failure, and providers must still store tokens as their interface requires.
Requests waiting for another request's update can cancel without stopping the shared operation. The request
that initiates the update still waits for the provider to finish, because ITokenHandler and ITokenStorage
do not accept cancellation tokens; it checks cancellation afterward and does not send a canceled HTTP request.
The coordination registry uses weak storage keys, so it does not permanently retain unused token stores.
GzipHandler
The GzipHandler is an implementation of DelegatingHandler that sends requests gzip compressed.
CompressedContent owns the content it wraps and disposes it when the compressed wrapper is disposed.
This lets request disposal release the original payload through the gzip pipeline. Compression still leaves
the destination stream open; callers must not reuse original content after disposing its compressed wrapper.
DependencyInjection
The AddDanglHttpClient<T>() method can be used to register an HttpClient with both an AuthenticationHandler
and a FallbackHandler via the HttpClientFactory pattern.
Assembly Strong Naming & Usage in Signed Applications
This module produces strong named assemblies when compiled. When consumers of this package require strongly named assemblies, for example when they
themselves are signed, the outputs should work as-is.
The key file to create the strong name is adjacent to the csproj file in the root of the source project. Please note that this does not increase
security or provide tamper-proof binaries, as the key is available in the source code per
Microsoft guidelines
Build and Markdown documentation
Build automation uses Fallout with the .NET 11 SDK. The bootstrap scripts use .fallout configuration and install .NET 11 when a compatible SDK is unavailable. The library retains its netstandard2.0 target for consumer compatibility.
Unit and integration tests target both .NET 10 and .NET 11 using xUnit v3 and Microsoft Testing Platform. Both test assemblies enable ParallelMode.All, including parallel execution of tests within a class. Install both runtimes to run the complete matrix; use dotnet test to run the tests or Coverage to also produce merged Jenkins test results and Cobertura coverage. Coverage output is isolated by project and target framework.
Test utilities use xUnit v3's ValueTask-based IAsyncLifetime. Consumers of IntegrationTestBase register the shared SQL fixture with [assembly: AssemblyFixture(typeof(SqlServerDockerCollectionFixture))] instead of the old ordering extension's IAssemblyFixture<T> interface.
BuildDocumentation generates the HTML site in output/docs and native DocFX Markdown API documentation, articles and assets in output/docs-markdown, with an adjacent ZIP archive. Start at index.md; API reference directories follow the HTML documentation's project scopes.
Both metadata entries in docfx.json use the library project's target framework without overriding it.
DocFX invocations preserve the build process environment and add DOCFX_SOURCE_BRANCH_NAME, so NuGet and MSBuild retain their profile, package-cache and temporary-directory settings.
TestMarkdownDocumentation checks native API preservation, archive layout, article links, resource globs, exclusions and missing entry-point errors without publishing.
UploadDocumentation uses Dangl.Fallout.WebDocu to upload the Markdown archive after HTML for the same explicit version. Existing API keys, branch gates, downloadable assets and version-conflict policies are preserved. Markdown documentation is available to AI agents through the DanglDocu MCP server.