- Notifications
You must be signed in to change notification settings - Fork 30
Custom Rate Limiting Policies
Cristi Pufu edited this page Aug 3, 2023 · 2 revisions
Check this out as well: https://github.com/dotnet/aspnetcore/issues/45603
Apply different rate limits based on http headers or user identity. Multi-tenant applications, user licensing, etc.
You can find the whole sample here: ClientIdRateLimiterPolicy.cs
public class ClientIdRateLimiterPolicy : IRateLimiterPolicy<string> { ... public ClientIdRateLimiterPolicy( IConnectionMultiplexer connectionMultiplexer, IServiceProvider serviceProvider) {} ... public RateLimitPartition<string> GetPartition(HttpContext httpContext) { var clientId = httpContext.Request.Headers["X-ClientId"].ToString(); using var scope = _serviceProvider.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService<SampleDbContext>(); var rateLimit = dbContext.Clients.Where(x => x.Identifier == clientId).Select(x => x.RateLimit).FirstOrDefault(); return RedisRateLimitPartition.GetRedisConcurrencyRateLimiter(clientId, key => new RedisConcurrencyRateLimiterOptions { PermitLimit = rateLimit.PermitLimit, QueueLimit = rateLimit.QueueLimit, ConnectionMultiplexerFactory = () => _connectionMultiplexer, }); } }