C
C#2y ago
Hulkstance

.NET 7 Rate Limit by IP address instead of Path

Pretty self explanatory title.
app.UseRateLimiter(new RateLimiterOptions
{
OnRejected = (context, _) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
context.HttpContext.Response.Headers.RetryAfter =
((int)retryAfter.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo);

app.Logger.LogWarning("Rate limit exceeded, retry after {RetryAfter} seconds", retryAfter.TotalSeconds);
}

context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;

return new ValueTask();
}
}
// You're allowed 2 requests per 10 seconds.
.AddFixedWindowLimiter("fixed",
new FixedWindowRateLimiterOptions(2,
window: TimeSpan.FromSeconds(10),
queueProcessingOrder: QueueProcessingOrder.OldestFirst,
queueLimit: 0,
autoReplenishment: true)));

app.MapControllers().RequireRateLimiting("fixed");
app.UseRateLimiter(new RateLimiterOptions
{
OnRejected = (context, _) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
context.HttpContext.Response.Headers.RetryAfter =
((int)retryAfter.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo);

app.Logger.LogWarning("Rate limit exceeded, retry after {RetryAfter} seconds", retryAfter.TotalSeconds);
}

context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;

return new ValueTask();
}
}
// You're allowed 2 requests per 10 seconds.
.AddFixedWindowLimiter("fixed",
new FixedWindowRateLimiterOptions(2,
window: TimeSpan.FromSeconds(10),
queueProcessingOrder: QueueProcessingOrder.OldestFirst,
queueLimit: 0,
autoReplenishment: true)));

app.MapControllers().RequireRateLimiting("fixed");
1 Reply
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View