public class RateLimitMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RateLimitMiddleware> _logger;
private readonly ConcurrentDictionary<string, DateTime> _requestDictionary;
public RateLimitMiddleware(RequestDelegate next, ILogger<RateLimitMiddleware> logger)
{
_next = next;
_logger = logger;
_requestDictionary = new ConcurrentDictionary<string, DateTime>();
}
public async Task InvokeAsync(HttpContext context)
{
var ipAddress = context.Connection.RemoteIpAddress?.ToString();
var currentTime = DateTime.UtcNow;
if (IsRateLimitExceeded(ipAddress, currentTime))
{
_logger.LogInformation($"Rate limit exceeded for IP address: {ipAddress}");
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
await context.Response.WriteAsync("Too many requests. Please try again later.");
return;
}
await _next(context);
_requestDictionary.AddOrUpdate(ipAddress, currentTime, (_, _) => currentTime);
}
private bool IsRateLimitExceeded(string ipAddress, DateTime currentTime)
{
if (_requestDictionary.TryGetValue(ipAddress, out var lastRequestTime))
{
var timeDifference = currentTime - lastRequestTime;
return timeDifference.TotalSeconds < 10;
}
return false;
}
}