stefanprodan / AspNetCoreRateLimit

ASP.NET Core rate limiting middleware
MIT License
3.12k stars 445 forks source link

[Question/Feature] Global endpoint rate limiting and specific API endpoint limitation #113

Open arnold-r-kiss opened 4 years ago

arnold-r-kiss commented 4 years ago

Hi,

And congrats for the work you are doing guys!

I would be interested in setting up the following configuration. I want a global limit applied for the entire suite of APIs of a maximum of 2 requests / sec. And I want to limit specific API endpoints for a maximum of 5 requests / min (those are triggering some background processing)

Is this possible with the current implementation of the framework? My understanding is that this is controlled by the EnableEndpointRateLimiting flag, which if I set it to false than I cannot apply limitations on specific endpoints( I can achieve my second requirement, but not the first one), if I set if to true all the rules will be applied for each endpoint (I can achieve my first requirement, but not the second one).

Thanks, Arnold K.

ram191 commented 4 years ago

I am facing a similar problem here. It would be great if we set the EnableEndpointRateLimiting to true, the endpoint of "*" would still be considered as a global rule for all endpoints. Is there any workaround for this at the moment?

mk1024 commented 3 years ago

I solved this by changing the EndpointCounterKeyBuilder property of RateLimitConfiguration from PathCounterKeyBuilder (default) to EndpointCounterKeyBuilder (see below). Now the counter keys are using the endpoint "*" instead of the path.

appsettings.json

"EnableEndpointRateLimiting": true

Startup.cs

services.AddSingleton<IRateLimitConfiguration, CustomRateLimitConfiguration>();

CustomRateLimitConfiguration.cs

public class CustomRateLimitConfiguration : RateLimitConfiguration
{
    public CustomRateLimitConfiguration(
        IHttpContextAccessor httpContextAccessor,
        IOptions<IpRateLimitOptions> ipOptions,
        IOptions<ClientRateLimitOptions> clientOptions)
        : base(httpContextAccessor, ipOptions, clientOptions) { }

    public override ICounterKeyBuilder EndpointCounterKeyBuilder
        => new EndpointCounterKeyBuilder();
}