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