1
1
using System . Security . Claims ;
2
2
using System . Threading . RateLimiting ;
3
+ using Microsoft . AspNetCore . RateLimiting ;
4
+ using Microsoft . Extensions . Options ;
3
5
4
6
namespace TodoApi ;
5
7
@@ -9,7 +11,25 @@ public static class RateLimitExtensions
9
11
10
12
public static IServiceCollection AddRateLimiting ( this IServiceCollection services )
11
13
{
12
- return services . AddRateLimiter ( options =>
14
+ services . AddRateLimiter ( ) ;
15
+
16
+ // Setup defaults for the TokenBucketRateLimiterOptions and read them from config if defined
17
+ // In theory this could be per user using named options
18
+ services . AddOptions < TokenBucketRateLimiterOptions > ( )
19
+ . Configure ( options =>
20
+ {
21
+ // Set defaults
22
+ options . ReplenishmentPeriod = TimeSpan . FromSeconds ( 10 ) ;
23
+ options . AutoReplenishment = true ;
24
+ options . TokenLimit = 100 ;
25
+ options . TokensPerPeriod = 100 ;
26
+ options . QueueLimit = 100 ;
27
+ } )
28
+ . BindConfiguration ( "RateLimiting" ) ;
29
+
30
+ // Setup the rate limiting policies taking the per user rate limiting options into account
31
+ services . AddOptions < RateLimiterOptions > ( )
32
+ . Configure ( ( RateLimiterOptions options , IOptionsMonitor < TokenBucketRateLimiterOptions > perUserRateLimitingOptions ) =>
13
33
{
14
34
options . RejectionStatusCode = StatusCodes . Status429TooManyRequests ;
15
35
@@ -20,17 +40,12 @@ public static IServiceCollection AddRateLimiting(this IServiceCollection service
20
40
21
41
return RateLimitPartition . GetTokenBucketLimiter ( username , key =>
22
42
{
23
- return new ( )
24
- {
25
- ReplenishmentPeriod = TimeSpan . FromSeconds ( 10 ) ,
26
- AutoReplenishment = true ,
27
- TokenLimit = 100 ,
28
- TokensPerPeriod = 100 ,
29
- QueueLimit = 100 ,
30
- } ;
43
+ return perUserRateLimitingOptions . CurrentValue ;
31
44
} ) ;
32
45
} ) ;
33
46
} ) ;
47
+
48
+ return services ;
34
49
}
35
50
36
51
public static IEndpointConventionBuilder RequirePerUserRateLimit ( this IEndpointConventionBuilder builder )
0 commit comments