Skip to content

Configuration

TurboHTTP is configured through TurboClientOptions — a mutable class covering connection pool settings and TLS configuration. Features like caching, retries, and redirects are composed separately via the fluent builder API returned by AddTurboHttpClient.

DI Registration

Register TurboHTTP in your ASP.NET Core or generic host application:

csharp
builder.Services.AddTurboHttpClient(options =>
{
    options.BaseAddress = new Uri("https://api.example.com");
    options.ConnectTimeout = TimeSpan.FromSeconds(5);
});

Inject ITurboHttpClientFactory wherever you need a client:

csharp
public class MyService(ITurboHttpClientFactory factory)
{
    public async Task<string> FetchAsync(CancellationToken ct)
    {
        var client = factory.CreateClient();
        var response = await client.SendAsync(
            new HttpRequestMessage(HttpMethod.Get, "/data"), ct);
        return await response.Content.ReadAsStringAsync(ct);
    }
}

Named Clients

Register multiple clients with different settings, then resolve by name:

csharp
// Public API — caching and redirect following enabled
builder.Services.AddTurboHttpClient("public-api", options =>
{
    options.BaseAddress = new Uri("https://api.example.com");
})
.WithCache()
.WithRedirect();

// Internal service — aggressive retries
builder.Services.AddTurboHttpClient("internal", options =>
{
    options.BaseAddress = new Uri("http://internal-service:8080");
})
.WithRetry(retry => { retry.MaxRetries = 5; });
csharp
var publicClient   = factory.CreateClient("public-api");
var internalClient = factory.CreateClient("internal");

TurboClientOptions Reference

Base Address

PropertyTypeDefault
BaseAddressUri?null

Relative HttpRequestMessage URIs are resolved against this base address. When null, all request URIs must be absolute.

csharp
options.BaseAddress = new Uri("https://api.example.com/v2/");

Connection Pool

PropertyTypeDefaultDescription
ConnectTimeoutTimeSpan00:00:15Timeout for establishing a new TCP connection
PooledConnectionIdleTimeoutTimeSpan00:01:30Time a connection may remain idle before eviction
PooledConnectionLifetimeTimeSpaninfiniteMaximum lifetime of a pooled connection
MaxEndpointSubstreamsuint256Maximum concurrently active endpoint substreams
csharp
options.ConnectTimeout = TimeSpan.FromSeconds(5);
options.PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2);
options.PooledConnectionLifetime = TimeSpan.FromMinutes(10);

HTTP/1.x Options

Per-version connection and protocol settings are configured on nested sub-objects:

PropertyTypeDefaultDescription
Http1.MaxConnectionsPerServerint6Maximum concurrent HTTP/1.x connections per host
Http1.MaxPipelineDepthint16Maximum pipelined requests per HTTP/1.1 connection
Http1.MaxBatchWeightint65536 (64 KiB)Max batch weight for request encoding
Http1.MaxResponseHeadersLengthint64 (KB)Max response header size
Http1.MaxReconnectAttemptsint3Max reconnect attempts on connection drop
csharp
options.Http1.MaxConnectionsPerServer = 12;  // raise for parallel HTTP/1.1
options.Http1.MaxPipelineDepth = 32;

HTTP/2 Options

PropertyTypeDefaultDescription
Http2.MaxConnectionsPerServerint6Maximum concurrent HTTP/2 connections per host
Http2.MaxConcurrentStreamsint100Maximum concurrent streams per connection
Http2.MaxFrameSizeint16384 (16 KiB)Maximum HTTP/2 frame payload size
Http2.HeaderTableSizeint4096HPACK dynamic table size
Http2.MaxBatchWeightint262144 (256 KiB)Max batch weight for frame encoding
Http2.MaxReconnectAttemptsint3Max reconnect attempts on connection drop

Increase frame size for workloads with large response bodies to reduce framing overhead:

csharp
options.Http2.MaxFrameSize = 4 * 1024 * 1024; // 4 MiB (default: 16 KiB)

HTTP/3 Options

PropertyTypeDefaultDescription
Http3.MaxConnectionsPerServerint4Maximum concurrent QUIC connections per host
Http3.QpackMaxTableCapacityint4096QPACK dynamic table size
Http3.QpackBlockedStreamsint100Max streams blocked waiting for QPACK
Http3.MaxFieldSectionSizeint65536 (64 KiB)Max header block size
Http3.IdleTimeoutTimeSpan00:00:30QUIC idle timeout
Http3.MaxReconnectAttemptsint3Max reconnect attempts on connection drop
Http3.AllowEarlyDataboolfalseAllow QUIC 0-RTT early data
Http3.AllowConnectionMigrationbooltrueAllow QUIC connection migration
Http3.AllowServerPushboolfalseAllow server push via PUSH_PROMISE
Http3.MaxBatchWeightint262144 (256 KiB)Max batch weight for frame encoding
Http3.EnableAltSvcDiscoveryboolfalseAuto-discover HTTP/3 via Alt-Svc headers

See HTTP/3 & QUIC guide for QUIC-specific configuration and Alt-Svc discovery.

TLS / HTTPS

PropertyTypeDefaultDescription
DangerousAcceptAnyServerCertificateboolfalseAccept all server certificates — dev/test only
ServerCertificateValidationCallbackRemoteCertificateValidationCallback?Accept SslPolicyErrors.None onlyCustom certificate validation
ClientCertificatesX509CertificateCollection?nullClient certificates for mutual TLS
EnabledSslProtocolsSslProtocolsSslProtocols.NoneTLS versions to enable (None = OS default)
csharp
// Accept a specific self-signed certificate by thumbprint (dev/staging)
options.ServerCertificateValidationCallback = (_, cert, _, errors) =>
    errors == SslPolicyErrors.None
    || cert?.GetCertHashString() == "ABCDEF1234567890";

// Mutual TLS (mTLS) with a client certificate
var cert = X509CertificateLoader.LoadPkcs12FromFile("client.pfx", password);
options.ClientCertificates = new X509CertificateCollection { cert };

WARNING

Setting DangerousAcceptAnyServerCertificate = true disables all certificate validation. Never use this in production.

Feature Configuration via Builder

Features are not set on TurboClientOptions. Instead, they are composed using the builder returned by AddTurboHttpClient:

csharp
builder.Services.AddTurboHttpClient("full-featured", options =>
{
    options.BaseAddress = new Uri("https://api.example.com");
})
.WithRedirect()              // follow redirects (default settings)
.WithRetry()                 // automatic retries
.WithCookies()               // automatic cookie management
.WithCache()                 // HTTP caching
.WithDecompression()         // gzip/deflate/brotli response decompression
.WithRequestCompression()    // gzip request body compression
.WithExpectContinue();       // Expect: 100-continue for large POST bodies

Redirect following

csharp
.WithRedirect()                                                          // default: max 10 redirects
.WithRedirect(r => { r.MaxRedirects = 3; })                              // custom limit

RedirectOptions properties:

PropertyTypeDefaultDescription
MaxRedirectsint10Maximum redirects before throwing an exception
AllowHttpsToHttpDowngradeboolfalseAllow redirects from HTTPS to HTTP

See Redirects guide for method rewriting and security behaviours.

Automatic retries

csharp
.WithRetry()                                                              // max 3 retries
.WithRetry(r => { r.MaxRetries = 5; r.RespectRetryAfter = false; })

RetryOptions properties:

PropertyTypeDefaultDescription
MaxRetriesint3Maximum retry attempts per request
RespectRetryAfterbooltrueHonour the server's Retry-After header

See Automatic Retries guide for which methods and status codes trigger retries.

HTTP caching

csharp
.WithCache()
.WithCache(c => { c.MaxEntries = 200; c.MaxBodyBytes = 5 * 1024 * 1024; })

To share a single store across multiple named clients, pass a CacheStore directly:

csharp
var sharedStore = new CacheStore();

builder.Services.AddTurboHttpClient("client-a", options => { ... }).WithCache(sharedStore);
builder.Services.AddTurboHttpClient("client-b", options => { ... }).WithCache(sharedStore);

CacheOptions properties:

PropertyTypeDefaultDescription
MaxEntriesint1000Maximum entries in the LRU store
MaxBodyByteslong52428800 (50 MiB)Maximum body size per cached response
SharedCacheboolfalseWhen true, acts as a shared (proxy) cache

See HTTP Caching guide for freshness evaluation and conditional request behaviour.

csharp
.WithCookies()             // private cookie jar per named client
.WithCookies(sharedJar)    // shared CookieJar across multiple clients

See Cookies guide for session and domain handling.

Response decompression

csharp
.WithDecompression()       // advertises Accept-Encoding: gzip, br, deflate and decompresses automatically
.WithDecompression(false)  // disable

Request compression and Expect: 100-continue

csharp
.WithRequestCompression()                                                              // gzip bodies >= 1 KiB
.WithRequestCompression(c => { c.Encoding = "br"; c.MinBodySizeBytes = 4096; })

.WithExpectContinue()                                                                  // Expect: 100-continue for bodies >= 1 KiB
.WithExpectContinue(e => { e.MinBodySizeBytes = 8192; })

See Content Encoding guide for details.

Complete Example

csharp
builder.Services.AddTurboHttpClient(options =>
{
    // Transport
    options.BaseAddress = new Uri("https://api.example.com");
    options.ConnectTimeout = TimeSpan.FromSeconds(5);
    options.PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2);

    // Per-version tuning
    options.Http1.MaxConnectionsPerServer = 10;
    options.Http2.MaxConcurrentStreams = 200;
})
.WithRedirect()
.WithRetry()
.WithCookies()
.WithCache()
.WithDecompression();

Released under the MIT License.