-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRateLimitingMiddleware.cs
More file actions
64 lines (54 loc) · 2.42 KB
/
Copy pathRateLimitingMiddleware.cs
File metadata and controls
64 lines (54 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
namespace ThrottleGuard;
public class RateLimitingMiddleware
{
private readonly RequestDelegate _next;
private readonly IDistributedCache _cache;
private readonly int _limitPerMinute;
private readonly int _cacheDurationSeconds;
private readonly int _warningThreshold;
private readonly int _responseDelayMilliseconds;
public RateLimitingMiddleware(RequestDelegate next, IDistributedCache cache, IConfiguration configuration)
{
_next = next;
_cache = cache;
// Load values from configuration
_limitPerMinute = configuration.GetValue<int>("RateLimiting:LimitPerMinute");
_cacheDurationSeconds = configuration.GetValue<int>("RateLimiting:CacheDurationSeconds");
_warningThreshold = configuration.GetValue<int>("RateLimiting:WarningThreshold");
_responseDelayMilliseconds = configuration.GetValue<int>("RateLimiting:ResponseDelayMilliseconds");
}
public async Task InvokeAsync(HttpContext context)
{
var ipAddress = context.Connection.RemoteIpAddress?.ToString();
var cacheKey = $"RateLimit_{ipAddress}";
var requestCount = await _cache.GetStringAsync(cacheKey);
int.TryParse(requestCount, out int count);
if (count >= _limitPerMinute)
{
// User exceeded the limit, block the request
context.Response.StatusCode = 429;
await context.Response.WriteAsync("Rate limit exceeded. Please wait before making more requests.");
return;
}
if (count >= _warningThreshold && count < _limitPerMinute)
{
// Graceful degradation: add artificial delay and send a warning
await Task.Delay(_responseDelayMilliseconds); // Delay based on configuration
// Set a custom header to warn about nearing the limit
context.Response.Headers.Append("X-RateLimit-Warning", "You are nearing the rate limit");
}
// Proceed with the normal request processing
await _next(context);
// Increment request count and update cache
count++;
await _cache.SetStringAsync(cacheKey, count.ToString(), new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1)
});
}
}