Linger.HttpClient.Standard 1.4.4-preview

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

Linger.HttpClient.Standard

Production-ready HTTP client implementation based on System.Net.Http.HttpClient.

Features

  • Zero Dependencies: Built on standard .NET libraries
  • HttpClientFactory Integration: Proper socket management and connection pooling
  • Proper Resource Management: Automatic disposal tracking with ownership pattern to prevent resource leaks
  • Streaming Download Support: DownloadStreamAsync and DownloadToFileAsync for large-file scenarios
  • Optional Response Mode: Buffered / Streamed response reading modes
  • Comprehensive Logging: Built-in performance monitoring
  • Linger.Results Integration: Seamless error mapping from server to client
  • ProblemDetails Support: Native RFC 7807 support

Installation

dotnet add package Linger.HttpClient.Standard

Quick Start

// Program.cs / Startup.cs
services.AddHttpClient<IHttpClient, StandardHttpClient>();

// In any business service
public sealed class UserQueryService
{
    private readonly IHttpClient _httpClient;

    public UserQueryService(IHttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<User?> GetAsync(int id, CancellationToken cancellationToken = default)
    {
        var result = await _httpClient.CallApi<User>($"api/users/{id}", cancellationToken: cancellationToken);

        if (result.IsSuccess && result.Data is not null)
        {
            return result.Data;
        }

        Console.WriteLine($"Request failed: {(int)result.StatusCode} - {result.ErrorMsg}");

        foreach (var error in result.Errors)
        {
            Console.WriteLine($"Error item: {error.Code} - {error.Message}");
        }

        return null;
    }
}

// Called from a controller or page
var user = await userQueryService.GetAsync(123);

if (user is not null)
{
    Console.WriteLine($"User: {user.Name}");
}
else
{
    Console.WriteLine("No user returned. Check the error output above.");
}

Key points:

  • Prefer HttpClientFactory in production.
  • Check ErrorMsg and Errors first when a call fails; do not rely on the status code alone.
  • Prefer DownloadStreamAsync / DownloadToFileAsync for large files.

Basic Usage

// Register in DI container
services.AddHttpClient<IHttpClient, StandardHttpClient>();

// Use in service
public class UserService
{
    private readonly IHttpClient _httpClient;

    public UserService(IHttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<User?> GetUserAsync(int id)
    {
        var result = await _httpClient.CallApi<User>($"api/users/{id}");
        return result.IsSuccess ? result.Data : null;
    }
}

Using Existing HttpClient Instance

If you already have an HttpClient instance (e.g., from HttpClientFactory), you can wrap it:

// The StandardHttpClient will NOT dispose the external HttpClient
var httpClient = httpClientFactory.CreateClient("MyClient");
using var standardClient = new StandardHttpClient(httpClient, logger);

var result = await standardClient.CallApi<User>("api/users/123");

Only use this approach for testing or simple scenarios:

// ⚠️ Creates new HttpClient instance
// StandardHttpClient will dispose it when disposed
using var client = new StandardHttpClient("https://api.example.com", logger);
var result = await client.CallApi<User>("api/users/123");
// HttpClient is automatically disposed here

Why HttpClientFactory is Recommended:

  • Proper connection pooling
  • Automatic DNS refresh handling
  • Prevents socket exhaustion
  • Built-in lifetime management

Linger.Results Integration

Integrates with Linger.Results for unified error handling:

// Server using Linger.Results
[HttpGet("{id}")]
public async Task<IActionResult> GetUser(int id)
{
    var result = await _userService.GetUserAsync(id);
    return result.ToActionResult(); // Automatic HTTP status mapping
}

// Client automatically receives structured errors
var apiResult = await _httpClient.CallApi<User>($"api/users/{id}");
if (!apiResult.IsSuccess)
{
    foreach (var error in apiResult.Errors)
        Console.WriteLine($"Error: {error.Code} - {error.Message}");
}

ProblemDetails Support

See the full request/response mapping and error contract in REQUEST_RESPONSE_MAPPING.zh-CN.md.

Short summary: the client prefers ProblemDetails.detail as the global message; if absent it uses the first message from errors (each errors value is an array). The Errors list preserves all individual error items for fine-grained handling.

Call Flow and Response Mapping

See REQUEST_RESPONSE_MAPPING.zh-CN.md for controller / minimal API examples and status-code mapping.

Custom Error Handling

StandardHttpClient can be inherited. If a server returns neither Linger.Results nor RFC 7807 ProblemDetails, override the error parsing logic to adapt custom formats.

The most common extension point is GetErrorMessageAsync in HttpClientBase, which converts the custom error body into ErrorMsg and Errors.

public class CustomHttpClient : StandardHttpClient
{
    public CustomHttpClient(HttpClient httpClient, ILogger<StandardHttpClient>? logger = null)
        : base(httpClient, logger)
    {
    }

    protected override async Task<(string ErrorMsg, IEnumerable<Error> Errors)> GetErrorMessageAsync(HttpResponseMessage response)
    {
        var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

        // Parse your custom error format here
        // Example: {"code":"BusinessRule","message":"Out of stock"}

        return await base.GetErrorMessageAsync(response).ConfigureAwait(false);
    }
}

Server Conventions

Follow these conventions for more stable error mapping:

  1. Response content type
  • Use application/problem+json for validation errors (RFC 7807).
  • Use an error array (IEnumerable<Error>) for business errors.
  1. Error payload structure
  • ProblemDetails: include title, status, and errors.
  • Error array: each item should include code and message.
  1. Status code conventions
  • Parameter or validation failure: 400 / 422
  • Unauthorized or authentication failure: 401 / 403
  • Resource not found: 404
  • Business conflict: 409

Core Methods

CallApi<T>

public async Task<ApiResult<T>> CallApi<T>(
    string url,
    HttpMethodEnum method,
    object? requestBody = null,
    object? queryParams = null,
    int? timeout = null,
    CancellationToken cancellationToken = default)

Supported HTTP methods:

  • GET: Retrieve data
  • POST: Create resource
  • PUT: Update resource
  • DELETE: Delete resource

Streaming Download

For large file downloads, use streaming methods to minimize memory consumption:

DownloadStreamAsync
// Download large file as stream (minimal memory usage)
var result = await _httpClient.DownloadStreamAsync("https://example.com/large-file.zip");
if (result.IsSuccess && result.Data is not null)
{
    using var stream = result.Data;
    // Process stream directly without loading entire file into memory
    // Remember to dispose the stream when done
}
// Download directly to file with progress reporting
var progress = new Progress<(long downloaded, long? total)>(p =>
{
    var percent = p.total.HasValue ? (double)p.downloaded / p.total.Value * 100 : 0;
    Console.WriteLine($"Downloaded: {p.downloaded} bytes ({percent:F1}%)");
});

var result = await _httpClient.DownloadToFileAsync(
    url: "https://example.com/large-file.zip",
    destinationPath: "output.zip",
    progress: progress
);

if (result.IsSuccess)
{
    Console.WriteLine("Download completed successfully!");
}

Benefits of Streaming Download:

  • ✅ Minimal memory usage (~8KB buffer vs full file size)
  • ✅ Supports files of any size
  • ✅ Built-in progress reporting
  • ✅ Cancellation token support

Performance Comparison (Downloading 500MB file):

Method Memory Usage Notes
CallApi<byte[]> ~500MB Loads entire file into memory
DownloadStreamAsync ~8KB Only buffer memory usage
DownloadToFileAsync ~8KB Customizable buffer size
HttpResponseMode (Buffered / Streamed)

Choose the response reading mode based on the scenario:

  • Buffered: Suitable for small responses or cases where the full content must be read at once
  • Streamed: Suitable for large responses or download scenarios, processing data incrementally with lower memory usage
Scenario Recommended Mode Reason
Regular JSON APIs (small to medium responses) Buffered Simple and easy to deserialize directly
File download / export Streamed Avoids loading the whole payload into memory and reduces peak memory usage
Potentially huge responses (logs, reports, binary data) Streamed More stable and reduces OOM risk
Need full content before unified processing Buffered Business logic is simpler

Performance comparison (downloading a 500 MB file):

Method Memory Usage Notes
CallApi<byte[]> ~500 MB Loads the entire file into memory
DownloadStreamAsync ~8 KB Buffer-only memory usage
DownloadToFileAsync ~8 KB Customizable buffer size

Error Handling

var result = await _httpClient.CallApi<User>("api/users/123");

if (result.IsSuccess)
{
    var user = result.Data;
}
else
{
    // Check HTTP status code
    switch (result.StatusCode)
    {
        case HttpStatusCode.NotFound:
            Console.WriteLine("User not found");
            break;
        case HttpStatusCode.Unauthorized:
            Console.WriteLine("Authentication required");
            break;
    }

    // Access detailed errors
    foreach (var error in result.Errors)
    {
        Console.WriteLine($"Error: {error.Code} - {error.Message}");
    }
}

Common Pitfalls

  • Do not use CallApi<byte[]> to download large files: it loads the entire response into memory.
  • Dispose the stream promptly after DownloadStreamAsync; using is recommended.
  • Pass a cancellation token to download tasks so timeouts or user cancellation can stop quickly.
  • Do not manage the lifecycle of an external HttpClient twice when wrapping an instance created by a factory.
  • Handle structured errors consistently and prefer the Errors list over status-code-only checks.

Best Practices

  • Use HttpClientFactory for dependency injection
  • Use using statements to ensure proper resource disposal
  • Enable detailed logging for debugging
  • Set reasonable timeout values
  • Handle network exceptions and timeouts
  • Use streaming methods for large file downloads (DownloadStreamAsync or DownloadToFileAsync) to save memory

More Examples

For complete streaming download examples and performance comparisons, see STREAMING_DOWNLOAD_EXAMPLE.md

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 is compatible.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.4.4-preview 28 6/16/2026
1.4.3-preview 44 6/15/2026
1.4.2 98 5/20/2026
1.4.1-preview 93 5/12/2026
1.4.0 97 5/6/2026
1.3.3-preview 85 5/5/2026
1.3.2-preview 98 4/29/2026
1.3.1-preview 92 4/28/2026
1.3.0-preview 92 4/27/2026
1.2.0-preview 109 3/29/2026
1.1.0 122 2/4/2026
1.0.3-preview 112 1/9/2026
1.0.2-preview 114 1/8/2026
1.0.0 316 11/12/2025
1.0.0-preview2 190 11/6/2025
1.0.0-preview1 184 11/5/2025
0.9.8 181 10/14/2025
0.9.7-preview 163 10/13/2025
0.9.6-preview 142 10/12/2025
0.9.5 146 9/28/2025
Loading failed