C#C
C#4y 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");
Was this page helpful?