Package Description
License
—
Deps
12
Install Size
—
Vulns
✓ 0
Published
Mar 3, 2026
$ dotnet add package Common.HttpClients一个功能丰富的HTTP客户端库,基于 Microsoft.Extensions.Http.Resilience 和 Polly,提供强大的弹性和韧性功能。
dotnet add package Common.HttpClients
// 使用默认配置
services.AddHttpClientService();
// 或自定义配置
services.AddHttpClientService(options =>
{
options.AuditLog = true; // 启用审计日志
options.FailThrowException = false; // 失败时不抛出异常,返回 null
options.Timeout = 30; // 自定义超时时间(秒),超时后会自动重试
options.MaxOutputResponseLength = 1024 * 1024; // 日志最大输出长度 1MB
options.IgnoreUntrustedCertificate = true; // 忽略不安全的SSL证书
options.RetryOnUnauthorized = true; // 401未授权错误时自动重试
});
public class MyService
{
private readonly IHttpHelper _httpHelper;
public MyService(IHttpHelper httpHelper)
{
_httpHelper = httpHelper;
}
public async Task<string> GetDataAsync()
{
var result = await _httpHelper.GetAsync<string>(Host + "/get?q1=11&q2=22");
return result;
}
}
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
AuditLog | bool | true | 是否启用审计日志 |
FailThrowException | bool | false | 失败时是否抛出异常。false 时返回 null,true 时抛出异常 |
Timeout | int | 100 | 超时时间(秒)。超时后会自动重试,最多重试3次 |
MaxOutputResponseLength | int | 0 | 日志最大输出响应长度(字节)。0 表示不限制,超过长度会截断 |
IgnoreUntrustedCertificate | bool | false | 是否忽略不安全的SSL证书 |
RetryOnUnauthorized | bool | false | 401未授权错误时是否重试 |
下面示例已经注入IHttpHelper
var result = await _httpHelper.GetAsync<string>(Host + "/get?q1=11&q2=22");还支持传递token以及传递请求头
支持传递字符串以及对象
var content = "{\"q\":\"123456\",\"a\":\"222\"}";
var result = await _httpHelper.PostAsync<string>(Host + "/post", content);using var form = new MultipartFormDataContent();
// bytes为文件字节数组
using var fileContent = new ByteArrayContent(bytes);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file", // 表单字段名称
FileName = fileName // 文件名
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent);
// 其他参数
using var content = new StringContent("其他参数值");
form.Add(content, "其他参数名称");
var requestUrl = $"{_difyApiBase}/v1/files/upload";
var response = await _httpHelper.PostFormDataAsync<FileUploadResponse>(requestUrl, form,
new Dictionary<string, string> { { "Authorization", $"Bearer {_difyApiKey}" } });可以设置配置AuditLog来设置是否启用审计日志,默认为启用状态。
builder.Services.AddHttpClientService();也可以为指定地址请求设置关闭审计日志,例如
var result = await _httpHelper.PostAsync<string>(Host + "/anything", list,
headers: new Dictionary<string, string>() { { "X-Logger", "skip" } });
var result2 = await _httpHelper.PostAsync<string>(Host + "/anything", list,
headers: new Dictionary<string, string>() { { "X-Skip-Logger", "" } });可以通过在请求头设置X-Skip-Logger或者设置X-Logger值为none、skip进行跳过日志
本库使用 Polly 实现了完整的弹性策略链,按以下顺序执行(从外层到内层):
当所有策略都失败时的最后保障:
FailThrowException = false:返回空响应,方法返回 nullFailThrowException = true:重新抛出原始异常限制同时进行的HTTP请求数量为 100,防止资源耗尽
自动重试失败的请求:
RetryOnUnauthorized = true)TimeoutException、TaskCanceledException、TimeoutRejectedException)HttpRequestException)当错误率达到阈值时暂时停止请求,保护下游系统
防止请求长时间阻塞:
Timeout 值(默认 100 秒)重要说明:超时策略放在最内层,每次重试都会应用超时限制。例如设置
Timeout = 30秒时,如果单次请求超过 30 秒会触发重试,最多重试 3 次,总计最长时间约为 90 秒(30s × 3次)+ 重试延迟。
本库自动支持分布式追踪,通过 X-Trace-Id 请求头传播追踪ID:
X-Trace-Id 请求头获取HttpContext.Request.Headers 中获取 X-Trace-IdHttpContext.TraceIdentifier所有日志都包含 TraceId,方便追踪整个请求链路:
Http请求开始.TraceId:a1b2c3d4e5f6 Url:https://api.example.com/data Method:GET
Http请求审计日志.TraceId:a1b2c3d4e5f6 Url:https://api.example.com/data Method:GET StatusCode:OK 耗时:1234.56ms
Timeout 值options.Timeout = 30;// 不设置 Timeout,使用默认值 100 秒options.RetryOnUnauthorized = true;options.FailThrowException = false;null 或 default(T)options.FailThrowException = true;