Token导航 LogoToken导航

Agent Skill · 前端设计

http-client-resilience(http 客户端弹性)

http-client-resilience 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

http-client-resilience 是前端设计类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描有提醒项,按安装量在前端设计类的 10,216 个 Skill 里排第 7,335。

总安装 388周安装 16GitHub Stars 15下载 127核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:http-client-resilience(http 客户端弹性)
来源仓库:https://github.com/wshaddix/dotnet-skills
仓库路径:skills/http-client-resilience
安装命令:
npx skills add https://github.com/wshaddix/dotnet-skills --skill http-client-resilience
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/wshaddix/dotnet-skills --skill http-client-resilience

这个 Skill 是做什么的

前端设计类 Skill 关注页面结构、视觉规范和组件写法,输出通常是可运行的界面代码。

用于增强 HTTP 客户端的容错与弹性处理能力。适合在 Codex、Claude、Cursor、Gemini CLI 中实现超时、重试与熔断。通过 GitHub 仓库安装,需引入 Polly 等弹性库支持。应根据业务容忍度设置合理的重试次数与退避策略。建议监控失败率并在达到阈值时告警。

http-client-resilience 属于前端设计类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/http-client-resilience

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/wshaddix/dotnet-skills --skill http-client-res…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

http-client-resilience 怎么安装?

在终端执行 npx skills add https://github.com/wshaddix/dotnet-skills --skill http-client-resilience。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

http-client-resilience 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

http-client-resilience 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

http-client-resilience 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

http-client-resilience 用的人多吗?

公开数据是累计安装 388 次,近一周安装 16 次,下载 127 次,GitHub 15 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

http-client-resilience 安全吗?

第三方扫描有提醒项,说明存在需要人工确认的行为。安装前请打开源码看清它读了什么、联网到哪里。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理前端设计类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

前端设计类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
frontend-design

前端设计 · Codex、Claude

8,823,360126,072只读MIT通过
vercel-composition-patterns

Vercel 组合模式 · Codex、Claude

3,858,81625,893需要联网MIT通过
vercel-react-native-skills

Vercel React native skills 前端 · Codex、Claude

2,468,66425,878只读MIT通过
adapt

adapt 搜索 · Codex、Claude

2,027,04023,125操作浏览器未明确通过
bolder

bolder 分析 · Codex、Claude

2,004,28823,130只读未明确通过
http-client-resilience

http 客户端弹性 · 本页

38815需要联网未明确有提醒

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Rationale

HTTP calls to external services are inherently unreliable. Network issues, service outages, and transient failures are common in distributed systems. Without proper resilience patterns, your application will experience cascading failures. These patterns using IHttpClientFactory and Polly provide production-grade reliability for HTTP communication.

Patterns

Pattern 1: Named HttpClient with Resilience

Configure named clients with comprehensive resilience policies including retry, circuit breaker, and timeout.

// Program.cs - Configuration
builder.Services.AddHttpClient("PaymentApi", client =>
{
    client.BaseAddress = new Uri("https://api.payment-provider.com/v1/");
    client.Timeout = TimeSpan.FromSeconds(30);
    client.DefaultRequestHeaders.Add("Accept", "application/json");
    client.DefaultRequestHeaders.Add("X-API-Key", builder.Configuration["PaymentApi:Key"]!);
})
.AddStandardResilienceHandler(options =>
{
    // Retry configuration
    options.Retry.MaxRetryAttempts = 3;
    options.Retry.Delay = TimeSpan.FromSeconds(1);
    options.Retry.BackoffType = DelayBackoffType.Exponential;

    // Circuit breaker configuration
    options.CircuitBreaker.SamplingDuration = TimeSpan.FromMinutes(1);
    options.CircuitBreaker.FailureRatio = 0.5;
    options.CircuitBreaker.MinimumThroughput = 10;
    options.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(30);

    // Timeout configuration
    options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(10);
    options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(30);
});

// Typed client for type-safe usage
public interface IPaymentClient
{
    Task<PaymentResult> ProcessPaymentAsync(PaymentRequest request, CancellationToken ct = default);
    Task<RefundResult> ProcessRefundAsync(string transactionId, CancellationToken ct = default);
}

public class PaymentClient : IPaymentClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<PaymentClient> _logger;

    public PaymentClient(IHttpClientFactory httpClientFactory, ILogger<PaymentClient> logger)
    {
        _httpClient = httpClientFactory.CreateClient("PaymentApi");
        _logger = logger;
    }

    public async Task<PaymentResult> ProcessPaymentAsync(PaymentRequest request, CancellationToken ct = default)
    {
        var response = await _httpClient.PostAsJsonAsync("payments", request, ct);

        if (response.StatusCode == HttpStatusCode.TooManyRequests)
        {
            _logger.LogWarning("Payment API rate limit hit");
            throw new PaymentRateLimitException("Payment provider is experiencing high load");
        }

        response.EnsureSuccessStatusCode();

        return await response.Content.ReadFromJsonAsync<PaymentResult>(ct)
            ?? throw new PaymentException("Invalid response from payment provider");
    }

    public async Task<RefundResult> ProcessRefundAsync(string transactionId, CancellationToken ct = default)
    {
        var response = await _httpClient.PostAsync($"payments/{transactionId}/refund", null, ct);
        response.EnsureSuccessStatusCode();

        return await response.Content.ReadFromJsonAsync<RefundResult>(ct)
            ?? throw new PaymentException("Invalid response");
    }
}

Pattern 2: Custom Resilience Pipeline with Polly

For advanced scenarios, build custom Polly pipelines with specific handling for different failure types.

// Custom resilience pipeline configuration
builder.Services.AddResiliencePipeline("critical-api", builder =>
{
    // Add retry with specific handling
    builder.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
    {
        MaxRetryAttempts = 5,
        Delay = TimeSpan.FromSeconds(2),
        BackoffType = DelayBackoffType.Exponential,
        ShouldHandle = args => args.Outcome switch
        {
            { Result: { StatusCode: HttpStatusCode.TooManyRequests } } => PredicateResult.True(),
            { Result: { StatusCode: HttpStatusCode.ServiceUnavailable } } => PredicateResult.True(),
            { Result: { StatusCode: HttpStatusCode.GatewayTimeout } } => PredicateResult.True(),
            { Exception: HttpRequestException } => PredicateResult.True(),
            { Exception: TimeoutRejectedException } => PredicateResult.True(),
            _ => PredicateResult.False()
        },
        OnRetry = args =>
        {
            Console.WriteLine($"Retry {args.AttemptNumber} for {args.Outcome.Result?.RequestMessage?.RequestUri}");
            return ValueTask.CompletedTask;
        }
    });

    // Add circuit breaker
    builder.AddCircuitBreaker(new CircuitBreakerStrategyOptions<HttpResponseMessage>
    {
        SamplingDuration = TimeSpan.FromMinutes(2),
        FailureRatio = 0.6,
        MinimumThroughput = 20,
        BreakDuration = TimeSpan.FromMinutes(2),
        ShouldHandle = args => args.Outcome.Result?.IsSuccessStatusCode is false
            ? PredicateResult.True()
            : PredicateResult.False(),
        OnOpened = args =>
        {
            Console.WriteLine($"Circuit opened! {args.FailureRatio * 100}% failure rate");
            return ValueTask.CompletedTask;
        },
        OnClosed = args =>
        {
            Console.WriteLine("Circuit closed - service recovered");
            return ValueTask.CompletedTask;
        }
    });

    // Add timeout per attempt
    builder.AddTimeout(TimeSpan.FromSeconds(15));
});

// Usage with typed client
public class InventoryClient
{
    private readonly HttpClient _httpClient;
    private readonly ResiliencePipeline<HttpResponseMessage> _pipeline;

    public InventoryClient(
        IHttpClientFactory factory,
        ResiliencePipelineProvider<HttpResponseMessage> pipelineProvider)
    {
        _httpClient = factory.CreateClient("InventoryApi");
        _pipeline = pipelineProvider.GetPipeline("critical-api");
    }

    public async Task<StockLevel> GetStockAsync(string sku, CancellationToken ct = default)
    {
        var response = await _pipeline.ExecuteAsync(
            async token => await _httpClient.GetAsync($"stock/{sku}", token),
            ct);

        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<StockLevel>(ct)
            ?? throw new InvalidOperationException("Invalid response");
    }
}

Pattern 3: Razor Pages Integration

Properly integrate HTTP clients in Razor Pages with proper disposal and error handling.

// Typed client registration
builder.Services.AddHttpClient<IGeoLocationService, GeoLocationService>(client =>
{
    client.BaseAddress = new Uri("https://api.geolocation.com/");
    client.Timeout = TimeSpan.FromSeconds(10);
})
.AddStandardResilienceHandler(options =>
{
    options.Retry.MaxRetryAttempts = 3;
    options.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(60);
});

// Service implementation
public interface IGeoLocationService
{
    Task<LocationInfo?> GetLocationAsync(string ipAddress, CancellationToken ct = default);
}

public class GeoLocationService : IGeoLocationService
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<GeoLocationService> _logger;

    public GeoLocationService(HttpClient httpClient, ILogger<GeoLocationService> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
    }

    public async Task<LocationInfo?> GetLocationAsync(string ipAddress, CancellationToken ct = default)
    {
        try
        {
            var response = await _httpClient.GetAsync($"json/{ipAddress}", ct);

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return null;
            }

            response.EnsureSuccessStatusCode();
            return await response.Content.ReadFromJsonAsync<LocationInfo>(ct);
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, "Failed to get location for IP {Ip}", ipAddress);
            return null; // Graceful degradation
        }
    }
}

// PageModel usage
public class AnalyticsModel : PageModel
{
    private readonly IGeoLocationService _geoService;
    private readonly ILogger<AnalyticsModel> _logger;

    [BindProperty]
    public LocationInfo? Location { get; set; }

    public string? ErrorMessage { get; set; }

    public async Task OnGetAsync()
    {
        var ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "8.8.8.8";

        try
        {
            Location = await _geoService.GetLocationAsync(ipAddress);

            if (Location is null)
            {
                ErrorMessage = "Unable to determine location";
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in analytics page");
            ErrorMessage = "Service temporarily unavailable";
        }
    }
}

Pattern 4: Request/Response Logging and Headers

Implement proper logging and custom headers for observability and authentication.

// Delegating handler for request/response logging
public class LoggingHandler : DelegatingHandler
{
    private readonly ILogger<LoggingHandler> _logger;

    public LoggingHandler(ILogger<LoggingHandler> logger)
    {
        _logger = logger;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var requestId = Guid.NewGuid().ToString("N")[..8];
        request.Headers.Add("X-Request-ID", requestId);

        _logger.LogInformation(
            "[{RequestId}] HTTP {Method} {Uri}",
            requestId,
            request.Method,
            request.RequestUri);

        var stopwatch = Stopwatch.StartNew();

        try
        {
            var response = await base.SendAsync(request, cancellationToken);
            stopwatch.Stop();

            _logger.LogInformation(
                "[{RequestId}] HTTP {StatusCode} in {ElapsedMs}ms",
                requestId,
                (int)response.StatusCode,
                stopwatch.ElapsedMilliseconds);

            return response;
        }
        catch (Exception ex)
        {
            stopwatch.Stop();
            _logger.LogError(
                ex,
                "[{RequestId}] HTTP request failed after {ElapsedMs}ms",
                requestId,
                stopwatch.ElapsedMilliseconds);
            throw;
        }
    }
}

// Authentication handler
public class ApiKeyHandler : DelegatingHandler
{
    private readonly string _apiKey;

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

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
        return base.SendAsync(request, cancellationToken);
    }
}

// Registration with handlers
builder.Services.AddTransient<LoggingHandler>();

builder.Services.AddHttpClient("SecureApi", (sp, client) =>
{
    client.BaseAddress = new Uri("https://api.secure-service.com/");
})
.AddHttpMessageHandler<LoggingHandler>()
.AddHttpMessageHandler(sp => new ApiKeyHandler(
    sp.GetRequiredService<IConfiguration>()["ApiKeys:SecureService"]!));

Pattern 5: Health Check Integration

Integrate HTTP client health checks for service monitoring.

// Custom health check for external services
public class ExternalApiHealthCheck : IHealthCheck
{
    private readonly IHttpClientFactory _httpClientFactory;

    public ExternalApiHealthCheck(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        try
        {
            var client = _httpClientFactory.CreateClient("PaymentApi");
            var response = await client.GetAsync("health", cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                return HealthCheckResult.Healthy("Payment API is accessible");
            }

            return HealthCheckResult.Degraded(
                $"Payment API returned {response.StatusCode}");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy(
                "Payment API is unreachable", ex);
        }
    }
}

// Registration in Program.cs
builder.Services.AddHealthChecks()
    .AddCheck<ExternalApiHealthCheck>("payment-api");

// Or use built-in URI health check
builder.Services.AddHealthChecks()
    .AddUrlGroup(
        new Uri("https://api.service.com/health"),
        name: "external-service",
        failureStatus: HealthStatus.Degraded,
        tags: new[] { "external" });

Anti-Patterns

// ❌ BAD: Using HttpClient directly with 'new'
var client = new HttpClient(); // Socket exhaustion!
var response = await client.GetAsync("https://api.example.com/data");

// ✅ GOOD: Use IHttpClientFactory
public class GoodService
{
    private readonly IHttpClientFactory _factory;

    public GoodService(IHttpClientFactory factory) => _factory = factory;

    public async Task GetDataAsync()
    {
        var client = _factory.CreateClient();
        var response = await client.GetAsync("https://api.example.com/data");
    }
}

// ❌ BAD: Static/shared HttpClient instance
public class BadService
{
    private static readonly HttpClient _client = new(); // DNS changes not respected!

    public async Task GetDataAsync()
    {
        var response = await _client.GetAsync("...");
    }
}

// ❌ BAD: No timeout handling
public async Task<string> FetchDataAsync()
{
    var client = _factory.CreateClient();
    var response = await client.GetAsync("https://slow-api.com/data"); // Hangs forever!
    return await response.Content.ReadAsStringAsync();
}

// ✅ GOOD: Set timeout and handle cancellation
public async Task<string?> FetchDataAsync(CancellationToken ct)
{
    var client = _factory.CreateClient();
    client.Timeout = TimeSpan.FromSeconds(10);

    try
    {
        var response = await client.GetAsync("https://slow-api.com/data", ct);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync(ct);
    }
    catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
    {
        _logger.LogError("Request timed out");
        return null;
    }
}

// ❌ BAD: Swallowing HTTP errors without context
try
{
    var response = await client.GetAsync("/api/data");
    return await response.Content.ReadFromJsonAsync<Data>();
}
catch (Exception ex)
{
    _logger.LogError(ex, "Request failed"); // No context about the failure
    return null;
}

// ✅ GOOD: Specific error handling with context
try
{
    var response = await client.GetAsync("/api/data", ct);

    if (response.StatusCode == HttpStatusCode.NotFound)
    {
        _logger.LogWarning("Data not found for ID {Id}", id);
        return null;
    }

    if (response.StatusCode == HttpStatusCode.TooManyRequests)
    {
        _logger.LogWarning("Rate limited by external API");
        throw new RateLimitException("Please try again later");
    }

    response.EnsureSuccessStatusCode();
    return await response.Content.ReadFromJsonAsync<Data>(ct);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.ServiceUnavailable)
{
    _logger.LogError(ex, "External service unavailable");
    throw new ServiceUnavailableException("Service temporarily unavailable");
}

// ❌ BAD: Not disposing HttpResponseMessage
var response = await client.GetAsync("/api/data");
return await response.Content.ReadAsStringAsync();

// ✅ GOOD: Proper disposal
using var response = await client.GetAsync("/api/data");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();

// ❌ BAD: Blocking in async context
public string GetData()
{
    var client = _factory.CreateClient();
    var response = client.GetAsync("/api/data").Result; // Deadlock risk!
    return response.Content.ReadAsStringAsync().Result;
}

// ✅ GOOD: Async all the way
public async Task<string> GetDataAsync(CancellationToken ct)
{
    var client = _factory.CreateClient();
    using var response = await client.GetAsync("/api/data", ct);
    return await response.Content.ReadAsStringAsync(ct);
}

References

平台分布

Codex

33.3%
按下载量换算42

Claude

32.68%
按下载量换算42

Cursor

21.08%
按下载量换算27

Gemini CLI

9.37%
按下载量换算12

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills