I have been implementing RateLimiting in dotnet 7, but when it reaches the limit it blocks all endpoints. I only want to block the one requested endpoint by the ip user when it get the limit.
This is my code in the Startup file in ConfigureServices:
services.AddRateLimiter(options =>
{
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(content =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: content.Request.Headers.Host.ToString(),
factory: partition => new FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 5,
QueueLimit = 0,
Window = TimeSpan.FromSeconds(20)
}
));
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});
You can try this ,you can modify your rate limiter implementation to use a per-endpoint rate limiter instead of a global rate limiter.
services.AddRateLimiter(options =>
{
options.EndpointLimiterFactory = (context, endpointKey) =>
PartitionedRateLimiter.Create<string, string>(key =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: key,
factory: partition => new FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 5,
QueueLimit = 0,
Window = TimeSpan.FromSeconds(20)
})
)(endpointKey);
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});
we're using the EndpointLimiterFactory property to create a new PartitionedRateLimiter instance for each endpoint. The endpointKey parameter is used as the partition key for the rate limiter.
With this configuration, each endpoint will have its own rate limiter instance, allowing you to enforce per-endpoint rate limits without blocking all endpoints when the rate limit is exceeded for a specific endpoint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With