CodexBloom - Programming Q&A Platform

C# 10 with ASP.NET Core: Issues with Custom Middleware for Rate Limiting Requests

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
c# aspnet-core middleware ratelimit C#

I've hit a wall trying to I'm implementing a custom middleware for rate limiting in my ASP.NET Core 6.0 application, but I'm encountering unexpected behavior. My middleware is supposed to limit users to 100 requests per minute based on their IP address. However, it seems to allow more requests than intended, especially when multiple requests are sent in quick succession. Here's the code for my middleware: ```csharp public class RateLimitingMiddleware { private readonly RequestDelegate _next; private static readonly Dictionary<string, int> _requestCounts = new Dictionary<string, int>(); private static readonly object _lock = new object(); private static readonly TimeSpan _timeSpan = TimeSpan.FromMinutes(1); private static readonly Dictionary<string, DateTime> _timestamps = new Dictionary<string, DateTime>(); public RateLimitingMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { var ipAddress = context.Connection.RemoteIpAddress.ToString(); lock (_lock) { if (_timestamps.TryGetValue(ipAddress, out DateTime lastRequestTime) && (DateTime.Now - lastRequestTime) < _timeSpan) { if (_requestCounts.ContainsKey(ipAddress) && _requestCounts[ipAddress] >= 100) { context.Response.StatusCode = StatusCodes.Status429TooManyRequests; return; } else { _requestCounts[ipAddress]++; } } else { _requestCounts[ipAddress] = 1; _timestamps[ipAddress] = DateTime.Now; } } await _next(context); } } ``` I've tried adding logging statements to see how many requests are counted, and it seems that when the time interval expires, the count is not reset as expected. For instance, if I send 105 requests within a minute, I receive a 429 status code only after the 100th request, but if I send requests shortly after that minute, I still get allowed through. I'm unsure if there's a threading issue or a logic flaw in how I'm managing timestamps and counts. I would appreciate any insights or suggestions on how to properly implement the rate limiting logic to ensure it correctly resets after the time interval. Is there a better pattern or approach I should consider for handling this kind of middleware functionality?