Configures Ocelot as an API Gateway in .NET with routing, aggregation, rate limiting, load balancing, and Consul/Kubernetes integration.
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.
dotnet add package Ocelot # Core — toujours requis
dotnet add package Ocelot.Provider.Consul # Service Discovery Consul
dotnet add package Ocelot.Provider.Eureka # Service Discovery Eureka
dotnet add package Ocelot.Cache.CacheManager # Cache distribué
dotnet add package Ocelot.Tracing.OpenTracing # Tracing distribué
// Program.cs (.NET 8+)
var builder = WebApplication.CreateBuilder(args);
// Charge ocelot.json en priorité sur appsettings.json
builder.Configuration
.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true)
.AddJsonFile($"ocelot.{builder.Environment.EnvironmentName}.json",
optional: true, reloadOnChange: true);
builder.Services
.AddOcelot(builder.Configuration)
.AddCacheManager(x => x.WithDictionaryHandle()) // cache en mémoire
.AddConsul() // si Consul utilisé
;
builder.Services.AddAuthentication()
.AddJwtBearer("Bearer", options =>
{
options.Authority = builder.Configuration["Jwt:Authority"];
options.Audience = builder.Configuration["Jwt:Audience"];
});
var app = builder.Build();
await app.UseOcelot();
app.Run();
Chaque route = un objet dans "Routes". Minima obligatoires :
{
"Routes": [
{
"DownstreamPathTemplate": "/api/payments/{everything}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "payment-service", "Port": 8080 }
],
"UpstreamPathTemplate": "/payments/{everything}",
"UpstreamHttpMethod": ["GET", "POST", "PUT", "DELETE"],
"AuthenticationOptions": {
"AuthenticationProviderKey": "Bearer"
},
"RateLimitOptions": {
"EnableRateLimiting": true,
"Period": "1m",
"PeriodTimespan": 60,
"Limit": 100
},
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3,
"DurationOfBreak": 10000,
"TimeoutValue": 5000
},
"FileCacheOptions": {
"TtlSeconds": 30,
"Region": "payments"
}
},
{
"DownstreamPathTemplate": "/api/orders/{everything}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "order-svc-1", "Port": 8080 },
{ "Host": "order-svc-2", "Port": 8080 }
],
"UpstreamPathTemplate": "/orders/{everything}",
"UpstreamHttpMethod": ["GET", "POST"],
"LoadBalancerOptions": { "Type": "RoundRobin" }
}
],
"GlobalConfiguration": {
"BaseUrl": "https://api.company.com",
"RateLimitOptions": {
"DisableRateLimitHeaders": false,
"QuotaExceededMessage": "Trop de requêtes, réessayez plus tard",
"HttpStatusCode": 429
}
}
}
Agrège plusieurs appels downstream en une seule réponse upstream. Utiliser la clé "Key" sur chaque route participante :
{
"Routes": [
{
"DownstreamPathTemplate": "/api/users/{userId}",
"UpstreamPathTemplate": "/users/{userId}",
"DownstreamHostAndPorts": [{ "Host": "user-svc", "Port": 8080 }],
"Key": "user"
},
{
"DownstreamPathTemplate": "/api/orders?userId={userId}",
"UpstreamPathTemplate": "/users/{userId}/orders",
"DownstreamHostAndPorts": [{ "Host": "order-svc", "Port": 8080 }],
"Key": "orders"
}
],
"Aggregates": [
{
"RouteKeys": ["user", "orders"],
"UpstreamPathTemplate": "/users/{userId}/profile"
}
]
}
Limite : l'agrégation ne supporte que GET. Pour des cas complexes (POST, transformation de payload), implémenter un custom
IDefinedAggregator.
builder.Services.AddOcelot().AddConsul();
{
"Routes": [
{
"DownstreamPathTemplate": "/api/{everything}",
"UpstreamPathTemplate": "/payments/{everything}",
"ServiceName": "payment-service",
"LoadBalancerOptions": { "Type": "LeastConnection" }
}
],
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Scheme": "http",
"Host": "consul",
"Port": 8500,
"Type": "Consul",
"PollingInterval": 5000
}
}
}
{
"AddHeadersToRequest": {
"X-Tenant-Id": "Claims[tenant_id] > value"
},
"AddClaimsToRequest": {
"sub": "Claims[sub] > value"
},
"AddQueriesToRequest": {
"clientId": "Claims[client_id] > value"
},
"UpstreamHeaderTransform": {
"X-Forwarded-For": "{RemoteIpAddress}"
},
"DownstreamHeaderTransform": {
"Location": "{DownstreamBaseUrl}/{UpstreamBaseUrl}"
}
}
// Middleware de corrélation avant Ocelot
app.Use(async (ctx, next) =>
{
ctx.Request.Headers["X-Correlation-Id"] =
ctx.Request.Headers.TryGetValue("X-Correlation-Id", out var existing)
? existing.ToString()
: Guid.NewGuid().ToString("N");
await next();
});
await app.UseOcelot();
| Critère | Ocelot | YARP |
|---|---|---|
| Configuration | JSON déclaratif | Code + config |
| Aggregation intégrée | Oui | Non (custom) |
| Service Discovery | Consul, Eureka | Custom |
| Performance | Bonne | Excellente (Microsoft) |
| Maintenance | Communauté | Microsoft officiel |
| Courbe d'apprentissage | Faible | Moyenne |
| Cas d'usage | Équipes petites/moyennes, config déclarative | Proxy haute performance, finops |
Choisir Ocelot si : config JSON suffisante, aggregation native requise, équipe habituée au routing déclaratif. Choisir YARP si : throughput critique (>50k req/s), besoin de transformations complexes en code.
Ne pas faire :
QoSOptions — un service lent bloque toute la gateway.ocelot.json pour tous les environnements — utiliser ocelot.{env}.json.FileCacheOptions) sur des routes POST/PUT/DELETE — effets de bord silencieux.207 Multi-Status et logger chaque sous-requête individuellement.8500) sur le réseau public.Jwt:Authority, clés API) en clair dans ocelot.json — utiliser les variables d'environnement ou un vault.Pièges courants :
UpstreamPathTemplate trop générique (/{everything}) capte tout et masque d'autres routes. Toujours ordonner du plus spécifique au plus général.reloadOnChange: true sur ocelot.json peut causer un reload à chaud en production ; tester en staging d'abord.QoSOptions) nécessite le package Polly — sans lui, les options sont ignorées silencieusement.ocelot.json avec le code source, jamais dans un ConfigMap Kubernetes non tracé./health et lier à la readiness probe.LeastConnection plutôt que RoundRobin dès que les services ont des latences inégales.Kube) plutôt que Consul sauf si multi-cluster.Ocelot.Tracing.OpenTracing) et les consommer dans Grafana.AddOcelot(builder.Configuration).What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/claude-skills-collection:api-gateway-ocelot-gateway-guidefrom 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