11using Microsoft . AspNetCore . Http ;
22using System ;
3- using System . Collections . Generic ;
4- using System . Net . Http ;
5- using System . Text ;
63using System . Threading . Tasks ;
7- using RateLimit . Throttlr . Core ;
84
95namespace RateLimit . Throttlr . Middleware
106{
@@ -16,6 +12,11 @@ internal class RateLimitingMiddleware
1612 private readonly RequestDelegate _next ;
1713 private readonly IRateLimiter _rateLimiter ;
1814
15+ private const string RetryAfter = "Retry-After" ;
16+ private const string RateLimitLimit = "X-RateLimit-Limit" ;
17+ private const string RateLimitRemaining = "X-RateLimit-Remaining" ;
18+ private const string RateLimitReset = "X-RateLimit-Reset" ;
19+
1920 public RateLimitingMiddleware ( RequestDelegate next , IRateLimiter rateLimiter )
2021 {
2122 _next = next ?? throw new ArgumentNullException ( nameof ( next ) ) ;
@@ -33,19 +34,19 @@ public async Task InvokeAsync(HttpContext context)
3334 context . Response . StatusCode = StatusCodes . Status429TooManyRequests ;
3435
3536 // Add standard rate limit headers
36- context . Response . Headers [ "Retry-After" ] = ( ( int ) result . RetryAfter . Value . TotalSeconds ) . ToString ( ) ;
37- context . Response . Headers [ "X-RateLimit-Limit" ] = _rateLimiter . GetLimit ( ) . ToString ( ) ;
38- context . Response . Headers [ "X-RateLimit-Remaining" ] = result . Remaining . ToString ( ) ;
39- context . Response . Headers [ "X-RateLimit-Reset" ] = result . Reset ? . ToUnixTimeSeconds ( ) . ToString ( ) ;
37+ context . Response . Headers [ RetryAfter ] = ( ( int ) result . RetryAfter . Value . TotalSeconds ) . ToString ( ) ;
38+ context . Response . Headers [ RateLimitLimit ] = _rateLimiter . GetLimit ( ) . ToString ( ) ;
39+ context . Response . Headers [ RateLimitRemaining ] = result . Remaining . ToString ( ) ;
40+ context . Response . Headers [ RateLimitReset ] = result . Reset ? . ToUnixTimeSeconds ( ) . ToString ( ) ;
4041
4142 await context . Response . WriteAsync ( "Too Many Requests" ) ;
4243 return ;
4344 }
4445
4546 // Attach useful headers on success
46- context . Response . Headers [ "X-RateLimit-Limit" ] = _rateLimiter . GetLimit ( ) . ToString ( ) ;
47- context . Response . Headers [ "X-RateLimit-Remaining" ] = result . Remaining . ToString ( ) ;
48- context . Response . Headers [ "X-RateLimit-Reset" ] = result . Reset ? . ToUnixTimeSeconds ( ) . ToString ( ) ;
47+ context . Response . Headers [ RateLimitLimit ] = _rateLimiter . GetLimit ( ) . ToString ( ) ;
48+ context . Response . Headers [ RateLimitRemaining ] = result . Remaining . ToString ( ) ;
49+ context . Response . Headers [ RateLimitReset ] = result . Reset ? . ToUnixTimeSeconds ( ) . ToString ( ) ;
4950
5051 await _next ( context ) ;
5152 }
0 commit comments