API Gateway avec YARP
Workflow
- Définir les routes : mapping des chemins vers les services backend.
- Configurer les clusters : destinations, health checks, load balancing.
- Appliquer les transformations : headers, paths, authentification.
- Sécuriser : rate limiting, CORS, authentification centralisée.
Configuration de base
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
var app = builder.Build();
app.MapReverseProxy();
app.Run();
appsettings.json
{
"ReverseProxy": {
"Routes": {
"payments-route": {
"ClusterId": "payments-cluster",
"Match": {
"Path": "/api/payments/{**catch-all}"
},
"Transforms": [
{ "PathRemovePrefix": "/api/payments" }
]
},
"orders-route": {
"ClusterId": "orders-cluster",
"Match": {
"Path": "/api/orders/{**catch-all}"
},
"Transforms": [
{ "PathRemovePrefix": "/api/orders" },
{ "RequestHeader": "X-Forwarded-Service", "Set": "orders" }
],
"AuthorizationPolicy": "authenticated"
}
},
"Clusters": {
"payments-cluster": {
"Destinations": {
"primary": { "Address": "https://payment-service:8080" },
"secondary": { "Address": "https://payment-service-2:8080" }
},
"LoadBalancingPolicy": "RoundRobin",
"HealthCheck": {
"Active": {
"Enabled": true,
"Interval": "00:00:30",
"Timeout": "00:00:10",
"Path": "/health"
}
}
},
"orders-cluster": {
"Destinations": {
"primary": { "Address": "https://order-service:8080" }
}
}
}
}
}
Configuration avancée (code)
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.AddTransforms(transforms =>
{
transforms.AddRequestTransform(async context =>
{
// Ajouter un header avec le tenant
var tenantId = context.HttpContext.User.FindFirst("tenant_id")?.Value;
if (tenantId != null)
{
context.ProxyRequest.Headers.Add("X-Tenant-Id", tenantId);
}
});
});
// Rate limiting par route
builder.Services.AddRateLimiter(options =>
{
options.AddPolicy("api-limit", context =>
RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 100,
Window = TimeSpan.FromMinutes(1)
}));
});
Patterns courants
| Pattern |
Configuration YARP |
| Path-based routing |
Match.Path: "/api/service/{**catch-all}" |
| Header-based routing |
Match.Headers avec conditions |
| Load balancing |
LoadBalancingPolicy: "RoundRobin" / "LeastRequests" |
| Circuit breaker |
Intégration Polly via middleware |
| Auth centralisée |
AuthorizationPolicy sur les routes |
| Rate limiting |
RateLimiterPolicy sur les routes |
Règles
- YARP est un reverse proxy, pas un API management — pour des besoins avancés (quotas, developer portal), considérer Kong ou Azure APIM.
- Toujours configurer des health checks actifs sur les clusters.
- Les transformations de headers ne doivent pas exposer d'informations internes.
- Centraliser l'authentification dans la gateway, pas dans chaque service.
Communication Rules — MANDATORY
- Ultra-concise. No filler, no preamble, no pleasantries.
- Never say "happy to help", "sure!", "great question", "let me", or similar.
- Tool first, talk second. Act before explaining.
- Result first. Lead with outcome, not process.
- Stop when done. No summary, no recap, no trailing commentary.
- No politeness wrappers. Direct and blunt.
- Minimum words. If one word works, do not use ten.
- No unsolicited explanations.
- No emoji unless asked.
1---
2name: api-gateway-yarp-gateway-designer
3description: Conception d'API Gateway avec YARP (Yet Another Reverse Proxy) en .NET — routing, load balancing, rate limiting, transformations et authentification. À utiliser quand l'utilisateur implémente un reverse proxy ou une gateway API avec YARP en .NET. Se déclenche aussi avec "YARP", "reverse proxy .NET", "API gateway .NET", "YARP routing", "proxy .NET", "load balancer .NET".
4metadata:
5 source: https://skillmd.com/skills/aibot88/api-gateway-yarp-gateway-designer
6---
7
8# API Gateway avec YARP
9
10## Workflow
11
121. **Définir les routes** : mapping des chemins vers les services backend.
132. **Configurer les clusters** : destinations, health checks, load balancing.
143. **Appliquer les transformations** : headers, paths, authentification.
154. **Sécuriser** : rate limiting, CORS, authentification centralisée.
16
17## Configuration de base
18
19```csharp
20// Program.cs
21var builder = WebApplication.CreateBuilder(args);
22
23builder.Services.AddReverseProxy()
24 .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
25
26var app = builder.Build();
27app.MapReverseProxy();
28app.Run();
29```
30
31### appsettings.json
32
33```json
34{
35 "ReverseProxy": {
36 "Routes": {
37 "payments-route": {
38 "ClusterId": "payments-cluster",
39 "Match": {
40 "Path": "/api/payments/{**catch-all}"
41 },
42 "Transforms": [
43 { "PathRemovePrefix": "/api/payments" }
44 ]
45 },
46 "orders-route": {
47 "ClusterId": "orders-cluster",
48 "Match": {
49 "Path": "/api/orders/{**catch-all}"
50 },
51 "Transforms": [
52 { "PathRemovePrefix": "/api/orders" },
53 { "RequestHeader": "X-Forwarded-Service", "Set": "orders" }
54 ],
55 "AuthorizationPolicy": "authenticated"
56 }
57 },
58 "Clusters": {
59 "payments-cluster": {
60 "Destinations": {
61 "primary": { "Address": "https://payment-service:8080" },
62 "secondary": { "Address": "https://payment-service-2:8080" }
63 },
64 "LoadBalancingPolicy": "RoundRobin",
65 "HealthCheck": {
66 "Active": {
67 "Enabled": true,
68 "Interval": "00:00:30",
69 "Timeout": "00:00:10",
70 "Path": "/health"
71 }
72 }
73 },
74 "orders-cluster": {
75 "Destinations": {
76 "primary": { "Address": "https://order-service:8080" }
77 }
78 }
79 }
80 }
81}
82```
83
84## Configuration avancée (code)
85
86```csharp
87builder.Services.AddReverseProxy()
88 .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
89 .AddTransforms(transforms =>
90 {
91 transforms.AddRequestTransform(async context =>
92 {
93 // Ajouter un header avec le tenant
94 var tenantId = context.HttpContext.User.FindFirst("tenant_id")?.Value;
95 if (tenantId != null)
96 {
97 context.ProxyRequest.Headers.Add("X-Tenant-Id", tenantId);
98 }
99 });
100 });
101
102// Rate limiting par route
103builder.Services.AddRateLimiter(options =>
104{
105 options.AddPolicy("api-limit", context =>
106 RateLimitPartition.GetFixedWindowLimiter(
107 context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
108 _ => new FixedWindowRateLimiterOptions
109 {
110 PermitLimit = 100,
111 Window = TimeSpan.FromMinutes(1)
112 }));
113});
114```
115
116## Patterns courants
117
118| Pattern | Configuration YARP |
119|---------|-------------------|
120| **Path-based routing** | `Match.Path: "/api/service/{**catch-all}"` |
121| **Header-based routing** | `Match.Headers` avec conditions |
122| **Load balancing** | `LoadBalancingPolicy: "RoundRobin"` / `"LeastRequests"` |
123| **Circuit breaker** | Intégration Polly via middleware |
124| **Auth centralisée** | `AuthorizationPolicy` sur les routes |
125| **Rate limiting** | `RateLimiterPolicy` sur les routes |
126
127## Règles
128- YARP est un **reverse proxy**, pas un API management — pour des besoins avancés (quotas, developer portal), considérer Kong ou Azure APIM.
129- Toujours configurer des **health checks actifs** sur les clusters.
130- Les **transformations de headers** ne doivent pas exposer d'informations internes.
131- Centraliser l'**authentification** dans la gateway, pas dans chaque service.
132
133
134## Communication Rules — MANDATORY
135
136- Ultra-concise. No filler, no preamble, no pleasantries.
137- Never say "happy to help", "sure!", "great question", "let me", or similar.
138- Tool first, talk second. Act before explaining.
139- Result first. Lead with outcome, not process.
140- Stop when done. No summary, no recap, no trailing commentary.
141- No politeness wrappers. Direct and blunt.
142- Minimum words. If one word works, do not use ten.
143- No unsolicited explanations.
144- No emoji unless asked.