Sage.Http 1.0.0.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package Sage.Http --version 1.0.0.1
                    
NuGet\Install-Package Sage.Http -Version 1.0.0.1
                    
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="Sage.Http" Version="1.0.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Sage.Http" Version="1.0.0.1" />
                    
Directory.Packages.props
<PackageReference Include="Sage.Http" />
                    
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 Sage.Http --version 1.0.0.1
                    
#r "nuget: Sage.Http, 1.0.0.1"
                    
#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 Sage.Http@1.0.0.1
                    
#: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=Sage.Http&version=1.0.0.1
                    
Install as a Cake Addin
#tool nuget:?package=Sage.Http&version=1.0.0.1
                    
Install as a Cake Tool

Sage.Http

简介

Sage.Http 是一个功能强大的 HTTP 客户端封装库,专为 .NET 应用程序设计,简化 HTTP 请求的发送和处理。该库提供了丰富的功能和灵活的 API,使开发人员能够轻松构建和管理 HTTP 请求。

主要特性

  • 多种设计模式支持

    • 工厂模式 - 通过 HttpRequestManagerFactory 创建实例
    • 单例模式 - 使用 HttpClientSingleton 确保全局唯一实例
    • 构建器模式 - 使用 HttpRequestBuilder 实现流式 API
  • 多种认证方式

    • API Key 认证 - 支持查询参数、请求头和请求体中的 API Key
    • Basic 认证 - 用户名和密码的 Base64 编码
    • Bearer Token 认证 - JWT 或 OAuth 令牌
    • 自定义认证 - 实现 IAuthenticationProvider 接口
  • 高级功能

    • 重试机制 - 可配置的重试策略,支持指数退避
    • 超时控制 - 精确的请求超时管理
    • 熔断器模式 - 防止系统过载和级联故障
    • 日志记录 - 详细的请求和响应日志
  • 灵活的请求处理

    • 同步和异步操作
    • JSON 序列化/反序列化
    • 文件上传和下载
    • 表单数据处理
    • 进度报告
  • 现代化特性

    • 完全兼容 AOT 编译
    • 支持 .NET 9.0
    • 支持 HTTP/3
    • 完全支持依赖注入

安装

NuGet 包管理器

Install-Package Sage.Http

.NET CLI

dotnet add package Sage.Http

使用示例

基本使用

using Sage.Http.Core;
using Sage.Http.Authentication;
using Microsoft.Extensions.Logging;
using System.Net.Http;

// 创建 HttpRequestManager
var httpClient = new HttpClient();
var logger = LoggerFactory.Create(builder => builder.AddConsole())
    .CreateLogger<HttpRequestManager>();
var requestManager = new HttpRequestManager(httpClient, logger);

// 设置认证
requestManager.SetDefaultAuthentication(new BearerTokenAuthProvider("your-token"));

// 发送 GET 请求
var response = await requestManager.GetAsync("https://api.example.com/data");
if (response.IsSuccessStatusCode)
{
    var content = await response.Content.ReadAsStringAsync();
    Console.WriteLine(content);
}

// 发送 POST 请求并反序列化 JSON 响应
var data = new { Name = "Test", Value = 123 };
var result = await requestManager.PostJsonAsync<ResponseType>("https://api.example.com/data", data);
Console.WriteLine($"Result: {result.Status}");

使用构建器模式

using Sage.Http.Core;
using Sage.Http.Authentication;

// 创建 HttpRequestManager
var requestManager = new HttpRequestManager(new HttpClient());

// 使用构建器模式构建请求
var response = await requestManager.CreateRequest(HttpMethod.Post, "https://api.example.com/users")
    .WithAuthentication(new BearerTokenAuthProvider("your-token"))
    .WithHeader("X-Custom-Header", "CustomValue")
    .WithJsonBody(new { Name = "John Doe", Email = "john@example.com" })
    .WithTimeout(TimeSpan.FromSeconds(30))
    .SendAsync();

// 处理响应
if (response.IsSuccessStatusCode)
{
    var user = await response.Content.ReadFromJsonAsync<UserModel>();
    Console.WriteLine($"Created user with ID: {user.Id}");
}

依赖注入与高级功能配置

// 在 Program.cs 或 Startup.cs 中配置服务

// 读取HTTP客户端配置
var httpClientSettings = builder.Configuration.GetSection("HttpClients").Get<HttpClientSettings>()
    ?? throw new InvalidOperationException("未找到HTTP客户端配置,请检查appsettings.json文件");

// 1. 注册HTTP客户端工厂
builder.Services.AddHttpRequestManagerFactory();

// 2. 注册Http客户端及配置服务(包括基础配置,重试、熔断)
builder.Services.AddHttpClientWithResilience(
    name: "ApiResourceServicesClient",
    configureClient: client =>
    {
        // 配置基本设置
        client.Timeout = TimeSpan.FromSeconds(httpClientSettings.ApiResourceServicesClient.TimeoutSeconds);
        client.DefaultRequestHeaders.Add("Accept", "application/json");
        
        // 开启HTTP/3支持
        client.DefaultRequestVersion = new Version(3, 0);
        client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower;
    },
    retryOptions: httpClientSettings.ApiResourceServicesClient.Retry, // 重试配置
    circuitBreakerOptions: httpClientSettings.ApiResourceServicesClient.CircuitBreaker // 熔断配置
);

在服务中使用注入的HttpRequestManager

public class UserService
{
    private readonly IHttpRequestManagerFactory _httpFactory;
    
    public UserService(IHttpRequestManagerFactory httpFactory)
    {
        _httpFactory = httpFactory;
    }
    
    public async Task<UserModel> GetUserAsync(int userId)
    {
        // 获取已配置的HttpRequestManager
        var httpManager = _httpFactory.CreateRequestManager("ApiResourceServicesClient");
        
        // 发送请求
        return await httpManager.GetJsonAsync<UserModel>($"https://api.example.com/users/{userId}");
    }
}

配置示例

appsettings.json 配置示例

{
  "HttpClients": {
    "ApiResourceServicesClient": {
      "TimeoutSeconds": 30,
      "Retry": {
        "Enabled": true,
        "MaxRetryCount": 3,
        "InitialDelayMs": 1000,
        "BackoffMultiplier": 2.0,
        "MaxDelayMs": 30000,
        "RetryStatusCodes": [408, 429, 500, 502, 503, 504]
      },
      "CircuitBreaker": {
        "Enabled": true,
        "FailureThreshold": 0.5,
        "SamplingDurationSeconds": 60,
        "MinimumThroughput": 10,
        "DurationOfBreakSeconds": 30
      }
    }
  }
}

API 参考

HttpRequestManager 核心方法

基础配置方法
// 更新 HttpClient 实例
requestManager.UpdateHttpClient(newHttpClient);

// 更新基础地址(允许修改初始化后的基础地址)
requestManager.UpdateBaseAddress(new Uri("https://api.newdomain.com"));

// 更新超时设置
requestManager.UpdateTimeout(TimeSpan.FromSeconds(60));

// 设置默认认证提供者
requestManager.SetDefaultAuthentication(new BearerTokenAuthProvider("your-token"));
同步请求方法
// 发送 GET 请求
var response = requestManager.Get("https://api.example.com/data");

// 发送 POST 请求
var postResponse = requestManager.Post("https://api.example.com/data", "{\"name\":\"value\"}", BodyType.Json);

// 发送 PUT 请求
var putResponse = requestManager.Put("https://api.example.com/data/1", "{\"name\":\"updated\"}");

// 发送 DELETE 请求
var deleteResponse = requestManager.Delete("https://api.example.com/data/1");

// 发送 PATCH 请求
var patchResponse = requestManager.Patch("https://api.example.com/data/1", "{\"name\":\"patched\"}");
异步请求方法
// 异步 GET 请求
var response = await requestManager.GetAsync("https://api.example.com/data");

// 异步 POST 请求
var postResponse = await requestManager.PostAsync("https://api.example.com/data", "{\"name\":\"value\"}");

// 异步 PUT 请求
var putResponse = await requestManager.PutAsync("https://api.example.com/data/1", "{\"name\":\"updated\"}");

// 异步 DELETE 请求
var deleteResponse = await requestManager.DeleteAsync("https://api.example.com/data/1");

// 异步 PATCH 请求
var patchResponse = await requestManager.PatchAsync("https://api.example.com/data/1", "{\"name\":\"patched\"}");
JSON 序列化/反序列化方法
// 发送 POST 请求并自动序列化对象为 JSON
var data = new { Name = "Test", Value = 123 };
var response = await requestManager.PostJsonAsync("https://api.example.com/data", data);

// 发送 GET 请求并自动反序列化 JSON 响应
var result = await requestManager.GetJsonAsync<UserModel>("https://api.example.com/users/1");

// 发送 POST 请求,序列化请求体并反序列化响应
var createResult = await requestManager.PostJsonAsync<CreateUserRequest, UserModel>(
    "https://api.example.com/users", 
    new CreateUserRequest { Name = "John", Email = "john@example.com" }
);

HttpRequestBuilder 构建器方法

// 创建请求构建器
var builder = requestManager.CreateRequest(HttpMethod.Post, "https://api.example.com/users");

// 添加认证
builder.AddAuthentication(new BearerTokenAuthProvider("your-token"));

// 添加请求头
builder.AddHeader("X-Custom-Header", "CustomValue");
builder.AddHeader("Accept-Language", "zh-CN");

// 添加查询参数
builder.AddQueryParameter("page", 1);
builder.AddQueryParameter("size", 20);
builder.AddQueryParameter("sort", "name,asc");

// 添加 JSON 请求体
builder.AddJsonBody(new { Name = "John Doe", Email = "john@example.com" });

// 添加表单字段
builder.AddFormField("username", "johndoe");
builder.AddFormField("password", "secret");

// 添加文件
var fileStream = File.OpenRead("document.pdf");
var fileParameter = new FileParameter(fileStream, "document.pdf", "application/pdf");
builder.AddFile("document", fileParameter);

// 设置进度报告
builder.SetProgress(new Progress<float>(p => Console.WriteLine($"Progress: {p:P2}")));

// 设置超时
builder.SetTimeout(TimeSpan.FromSeconds(30));

// 设置取消令牌
var cts = new CancellationTokenSource();
builder.SetCancellationToken(cts.Token);

// 发送请求
var response = await builder.SendAsync();

高级用法

文件上传

// 创建文件参数
var fileStream = File.OpenRead("document.pdf");
var fileParameter = new FileParameter(fileStream, "document.pdf", "application/pdf");

// 使用构建器上传文件
var response = await requestManager.CreateRequest(HttpMethod.Post, "https://api.example.com/upload")
    .AddAuthentication(new BearerTokenAuthProvider("your-token"))
    .AddFile("file", fileParameter)
    .AddFormField("description", "Important document")
    .SetProgress(new Progress<float>(p => Console.WriteLine($"Upload progress: {p:P2}")))
    .SendAsync();

自定义认证提供者

// 实现自定义认证提供者
public class ApiKeyAuthProvider : IAuthenticationProvider
{
    private readonly string _apiKey;

    public ApiKeyAuthProvider(string apiKey)
    {
        _apiKey = apiKey;
    }

    public Task ApplyAuthenticationAsync(HttpRequestMessage request)
    {
        request.Headers.Add("X-API-Key", _apiKey);
        return Task.CompletedTask;
    }
}

// 使用自定义认证提供者
var response = await requestManager.GetAsync("https://api.example.com/data", new ApiKeyAuthProvider("your-api-key"));

// 或者在构建器中使用
var response = await requestManager.CreateRequest(HttpMethod.Get, "https://api.example.com/data")
    .AddAuthentication(new ApiKeyAuthProvider("your-api-key"))
    .SendAsync();

// 设置为默认认证提供者
requestManager.SetDefaultAuthentication(new ApiKeyAuthProvider("your-api-key"));

多部分表单提交

// 创建多部分表单请求
var response = await requestManager.CreateRequest(HttpMethod.Post, "https://api.example.com/submit-form")
    .AddFormField("name", "John Doe")
    .AddFormField("email", "john@example.com")
    .AddFormField("message", "Hello, this is a test message")
    .AddFile("attachment", new FileParameter(File.OpenRead("document.pdf"), "document.pdf", "application/pdf"))
    .AddFile("image", new FileParameter(File.OpenRead("image.jpg"), "image.jpg", "image/jpeg"))
    .SendAsync();

请求进度跟踪

// 创建进度报告对象
var progress = new Progress<float>(p => 
{
    Console.WriteLine($"请求进度: {p:P2}");
    // 更新UI进度条或其他进度指示器
});

// 在请求中使用进度报告
var response = await requestManager.CreateRequest(HttpMethod.Post, "https://api.example.com/upload")
    .AddFile("file", new FileParameter(File.OpenRead("largefile.zip"), "largefile.zip", "application/zip"))
    .SetProgress(progress)
    .SendAsync();

错误处理与高级配置

异常处理

try
{
    var response = await requestManager.GetAsync("https://api.example.com/data");
    response.EnsureSuccessStatusCode(); // 抛出非成功状态码的异常
    var content = await response.Content.ReadAsStringAsync();
    // 处理响应内容
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
    // 处理 404 错误
    Console.WriteLine("请求的资源不存在");
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Unauthorized)
{
    // 处理 401 错误
    Console.WriteLine("认证失败,请检查凭据");
}
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
{
    // 处理超时异常
    Console.WriteLine("请求超时");
}
catch (Exception ex)
{
    // 处理其他异常
    Console.WriteLine($"发生错误: {ex.Message}");
}

请求重试与熔断高级配置

// 在 appsettings.json 中配置
{
  "HttpClientOptions": {
    "MyClient": {
      "Timeout": 30,
      "Retry": {
        "MaxRetryCount": 3,
        "InitialDelaySeconds": 1,
        "MaxDelaySeconds": 5,
        "DelayFactor": 2.0,
        "RetryStatusCodes": [408, 429, 500, 502, 503, 504],
        "RetryHttpMethods": ["GET", "HEAD", "OPTIONS", "TRACE", "PUT", "DELETE"]
      },
      "CircuitBreaker": {
        "FailureThreshold": 0.5,
        "SamplingDurationSeconds": 30,
        "MinimumThroughput": 10,
        "DurationOfBreakSeconds": 30,
        "StatusCodesToTrack": [500, 502, 503, 504]
      }
    }
  }
}

// 在代码中使用自定义配置
services.AddHttpClientWithResilience("MyClient", client => { }, options =>
{
    // 自定义重试配置
    options.Retry.MaxRetryCount = 5;
    options.Retry.InitialDelaySeconds = 2;
    options.Retry.RetryStatusCodes = new[] { 408, 429, 500, 502, 503, 504 };
    
    // 自定义熔断配置
    options.CircuitBreaker.FailureThreshold = 0.3; // 30% 失败率触发熔断
    options.CircuitBreaker.DurationOfBreakSeconds = 60; // 熔断持续 60 秒
});

常见问题

Q: 如何处理大文件下载?

使用进度报告功能和流式处理:

var response = await requestManager.GetAsync("https://api.example.com/large-file");

if (response.IsSuccessStatusCode)
{
    using var stream = await response.Content.ReadAsStreamAsync();
    using var fileStream = File.Create("downloaded-file.zip");
    
    // 使用缓冲区复制流以提高性能
    byte[] buffer = new byte[81920]; // 80KB 缓冲区
    int bytesRead;
    long totalBytesRead = 0;
    long? fileSize = response.Content.Headers.ContentLength;
    
    // 创建进度报告
    var progress = new Progress<float>(p => Console.WriteLine($"下载进度: {p:P2}"));
    
    while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
    {
        await fileStream.WriteAsync(buffer, 0, bytesRead);
        totalBytesRead += bytesRead;
        
        // 报告进度
        if (fileSize.HasValue && fileSize.Value > 0)
        {
            float progressValue = (float)totalBytesRead / fileSize.Value;
            ((IProgress<float>)progress).Report(progressValue);
        }
    }
}

Q: 如何设置全局默认超时?

在创建 HttpClient 时设置默认超时:

var httpClient = new HttpClient
{
    Timeout = TimeSpan.FromSeconds(30)
};

var requestManager = new HttpRequestManager(httpClient);
// 创建 Cookie 容器
var cookieContainer = new CookieContainer();

// 创建 HttpClientHandler 并设置 Cookie 容器
var handler = new HttpClientHandler
{
    CookieContainer = cookieContainer,
    UseCookies = true
};

// 创建 HttpClient 并传递 handler
var httpClient = new HttpClient(handler);
var requestManager = new HttpRequestManager(httpClient);

// 添加 Cookie
cookieContainer.Add(new Uri("https://api.example.com"), new Cookie("session", "abc123"));

// 发送请求
var response = await requestManager.GetAsync("https://api.example.com/data");

// 获取响应中的 Cookie
var cookies = cookieContainer.GetCookies(new Uri("https://api.example.com"));
foreach (Cookie cookie in cookies)
{
    Console.WriteLine($"{cookie.Name}: {cookie.Value}");
}

许可证

本项目采用 Apache 2.0 许可证。详情请参阅 LICENSE 文件。

版权所有 © 2025 甲壳虫科技团队。

联系方式

  • QQ 群: 1054304346
  • 邮箱: 100576208@qq.com

作者

甲壳虫科技团队 - 专注于打造高质量的 .NET 开发工具和库

Product Compatible and additional computed target framework versions.
.NET 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 was computed.  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. 
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 Sage.Http:

Package Downloads
Sage.CloudStorage.Qiniu

Sage.CloudStorage.Qiniu 是一个基于 .NET 平台的现代化七牛云存储 SDK,采用完全异步设计,提供了对七牛云对象存储、CDN 等服务的简单易用的 API 封装。该库基于 Sage.Http 构建,具有高性能、可扩展的七牛云服务访问能力,特别适合企业级应用和大文件处理场景。 ## 核心优势 - **现代化API设计**:完全异步,符合.NET最佳实践 - **模块化架构**:各组件职责明确,易于扩展和维护 - **丰富的事件机制**:提供上传进度通知和完成事件 - **智能上传策略**:自动选择最佳上传方式和分片大小 - **完善的错误处理**:提供详细的错误信息和恢复机制 ## 功能特性 - **完整的对象存储支持**:上传、下载、管理、删除等操作 - **高级上传功能**: - 智能分片上传(自动优化分片大小) - 断点续传支持 - 并发控制 - 实时进度监控 - **CDN管理**:刷新、预取、带宽查询、日志下载 - **数据处理**:图片处理、音视频转码等 - **批量操作**:批量上传、删除等

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0.5 22 9/23/2025
1.0.0.4 197 8/27/2025
1.0.0.3 250 8/25/2025
1.0.0.1 124 8/21/2025
1.0.0 130 7/16/2025

修复了命名空间存在错误的小疏忽