Designs API Gateways with YARP in .NET — routing, load balancing, rate limiting, transforms, and authentication. Useful when implementing a reverse proxy or gateway in ASP.NET Core.
Ships in claude-skills-collection. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
| Besoin | Recommandation |
|---|---|
| Reverse proxy léger, intégré .NET | YARP |
| Developer portal, quotas avancés, monétisation | Azure APIM ou Kong |
| Multi-tenant avec isolation stricte | YARP + middleware tenant + JWT claims |
| mTLS entre gateway et backends | YARP + HttpClient custom avec cert |
dotnet add package Yarp.ReverseProxy
# Dernière version stable : 2.2.0 (LTS .NET 8/9)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
// Optionnel : rate limiting (Microsoft.AspNetCore.RateLimiting)
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("api-limit", opt =>
{
opt.PermitLimit = 100;
opt.Window = TimeSpan.FromMinutes(1);
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
opt.QueueLimit = 10;
});
options.RejectionStatusCode = 429;
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
app.MapReverseProxy();
app.Run();
{
"ReverseProxy": {
"Routes": {
"payments-route": {
"ClusterId": "payments-cluster",
"Match": { "Path": "/api/payments/{**catch-all}" },
"Transforms": [
{ "PathRemovePrefix": "/api/payments" },
{ "RequestHeader": "X-Gateway-Source", "Set": "yarp-gw" }
],
"RateLimiterPolicy": "api-limit",
"AuthorizationPolicy": "anonymous"
},
"orders-route": {
"ClusterId": "orders-cluster",
"Match": {
"Path": "/api/orders/{**catch-all}",
"Headers": [{ "Name": "X-Api-Version", "Values": ["v2"], "Mode": "ExactHeader" }]
},
"Transforms": [
{ "PathRemovePrefix": "/api/orders" }
],
"AuthorizationPolicy": "authenticated",
"RateLimiterPolicy": "api-limit"
}
},
"Clusters": {
"payments-cluster": {
"LoadBalancingPolicy": "RoundRobin",
"HealthCheck": {
"Active": {
"Enabled": true,
"Interval": "00:00:30",
"Timeout": "00:00:10",
"Path": "/health"
},
"Passive": { "Enabled": true }
},
"Destinations": {
"primary": { "Address": "https://payment-svc-1:8080" },
"secondary": { "Address": "https://payment-svc-2:8080" }
}
},
"orders-cluster": {
"LoadBalancingPolicy": "LeastRequests",
"Destinations": {
"primary": { "Address": "https://order-svc:8080" }
}
}
}
}
}
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.AddTransforms(ctx =>
{
// Injecter le tenant depuis le JWT dans chaque requête proxiée
ctx.AddRequestTransform(async reqCtx =>
{
var tenantId = reqCtx.HttpContext.User.FindFirst("tenant_id")?.Value;
if (tenantId is not null)
reqCtx.ProxyRequest.Headers.TryAddWithoutValidation("X-Tenant-Id", tenantId);
// Corrélation
var correlationId = reqCtx.HttpContext.TraceIdentifier;
reqCtx.ProxyRequest.Headers.TryAddWithoutValidation("X-Correlation-Id", correlationId);
});
// Masquer les headers internes sur la réponse
ctx.AddResponseTransform(async respCtx =>
{
respCtx.ProxyResponse?.Headers.Remove("X-Internal-Node");
await Task.CompletedTask;
});
});
// Besoin : Microsoft.Extensions.Http.Resilience
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.ConfigureHttpClient((ctx, handler) =>
{
// Timeout global par requête proxiée
handler.ActivityHeadersPropagator = null;
})
.AddResilienceHandler("circuit-breaker", builder =>
{
builder.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
{
SamplingDuration = TimeSpan.FromSeconds(30),
FailureRatio = 0.5,
MinimumThroughput = 10,
BreakDuration = TimeSpan.FromSeconds(15)
});
builder.AddTimeout(TimeSpan.FromSeconds(5));
});
// Recharger les routes/clusters depuis n'importe quelle source dynamique
var proxyConfig = app.Services.GetRequiredService<InMemoryConfigProvider>();
proxyConfig.Update(newRoutes, newClusters);
// Pas besoin de redémarrer le process — YARP recharge instantanément.
Pour un chargement depuis une base de données ou un API config, implémenter IProxyConfigProvider.
| Cas | Config YARP |
|---|---|
| Path prefix routing | Match.Path: "/api/svc/{**catch-all}" + PathRemovePrefix |
| Header-based routing (versioning) | Match.Headers[].Values + Mode: ExactHeader |
| Query string routing | Match.QueryParameters[].Values |
| Host-based routing (multi-tenant) | Match.Hosts: ["tenant1.api.com"] |
| Weighted routing (canary) | Deux destinations, Weight dans les clusters |
| Rewrite complet de chemin | PathPattern: "/v2/{**catch-all}" |
| Politique | Usage |
|---|---|
RoundRobin | Distribution uniforme, cas général |
LeastRequests | Backends hétérogènes (latence variable) |
Random | Tests, benchmarks |
PowerOfTwoChoices | Haute charge, meilleure distribution que RoundRobin |
FirstAlphabetical | Failover ordonné, actif/passif |
Ne pas faire :
AuthorizationPolicy sur des endpoints sensibles (oubli silencieux — YARP ne bloque rien par défaut).PassiveHealthCheck : sans lui, un backend tombé reste dans la rotation jusqu'au prochain active check.HttpClient timeout à l'infini — toujours positionner un timeout explicite (AddTimeout).X-Internal-*, Server, X-Powered-By) aux clients — les supprimer dans AddResponseTransform.appsettings.json — utiliser IConfiguration + Azure Key Vault / environment variables.Pièges courants :
PathRemovePrefix est case-sensitive — tester avec /Api/Payments vs /api/payments si les clients varient.Order explicite sur chaque route si la priorité compte.AddReverseProxy().LoadFromConfig() et AddTransforms() doivent être chaînés sur le même IReverseProxyBuilder, sinon les transforms ne s'appliquent pas.UseRateLimiter() doit être appelé avant MapReverseProxy() dans le pipeline.Yarp.ReverseProxy activity source) — les brancher sur Prometheus/Grafana ou Azure Monitor.SocketsHttpHandler avec le certificat client dans ConfigureHttpClient.IProxyConfigProvider avec rechargement depuis un config store (Consul, Azure App Configuration) plutôt que des restart.Accept-Version ou par host v2.api.company.com plutôt que par path quand les backends sont stables.Microsoft.AspNetCore.TestHost + WebApplicationFactory pour tester les routes YARP sans démarrer de vrai serveur backend (mocker les destinations avec WireMock.Net).What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/claude-skills-collection:api-gateway-yarp-gateway-designerfrom claude-skills-collection
npx claudepluginhub vantaflow/claude-skills-collection --plugin claude-skills-collection348 skills in this plugin
/agent-a2a-protocol-guideGuide du protocole Agent-to-Agent (A2A) de Google pour l'interopérabilité entre agents IA — découverte, communication et collaboration inter-agents, avec exemples de code, critères de décision et pièges à éviter. Se déclenche avec "A2A", "agent-to-agent", "protocole A2A", "Google A2A", "interopérabilité agents". Also triggers on "agent-to-agent protocol", "agent interoperability", "connect two agents"./agent-agent-observabilityInstrumentation technique d'un agent IA — tracing distribué des appels LLM et outils, spans, métriques custom, corrélation de logs et dashboards de supervision. Pour les alertes et garde-fous de production, voir agent-monitoring-setup. Se déclenche avec "observabilité agent", "tracing agent", "LangSmith", "Langfuse", "OpenTelemetry agent", "spans LLM", "corréler les logs agent". Also triggers on "trace my agent", "LLM tracing", "agent spans"./agent-api-caller-subagentSous-agent spécialisé dans les appels API REST/GraphQL avec retry, auth et transformation de données. Se déclenche avec "sous-agent API", "API caller agent", "agent qui appelle une API", "REST agent", "HTTP agent", "API integration subagent", "external API agent". Also triggers on "subagent that calls an API", "API calling agent", "agent HTTP requests".Other plugins' skills for the same job