Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.NET 7 Rate Limiting – Rate limit by IP

I want to set rate limit by user IP so in 1 minute he can send only 3 requests.

Also I want to set this to particular end-point. I have tried below code but it is not working.. so any idea on this..

I am using .NET Core 7

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Program.cs file

builder.Services.AddRateLimiter(options =>
{
    options.AddPolicy("testRatelimit", context => RateLimitPartition.GetFixedWindowLimiter(
        partitionKey: context.User.Identity?.Name ?? context.Request.Headers.Host.ToString(),
        factory: partition => new FixedWindowRateLimiterOptions
        {
            AutoReplenishment = true,
            PermitLimit = 3,
            QueueLimit = 0,
            Window = TimeSpan.FromMinutes(1)
        }));

    options.OnRejected = async (context, token) =>
    {
        context.HttpContext.Response.StatusCode = 429;
        await context.HttpContext.Response.WriteAsync("Too many requests. Please try later again... ", cancellationToken: token);
    };
});


var app = builder.Build();
app.UseRateLimiter();

In my controller I have added in thi way :

[EnableRateLimiting("testRatelimit")]
        [AllowAnonymous]
        [HttpPost]
        [Route("forgot-password")]
        public async Task<IActionResult> ForgotPassword(string email, bool? isAdmin)
        {
            return Ok(await userService.ForgotPassword(email, isAdmin ?? false));
        }

>Solution :

I want to set rate limit by user IP so in 1 minute he can send only 3 requests.

Then you need to use IP as partitioning key, not the context.User.Identity?.Name ?? context.Request.Headers.Host.ToString(). Try something like:

options.AddPolicy("testRatelimit", context => RateLimitPartition.GetFixedWindowLimiter(
    partitionKey: context.Connection.RemoteIpAddress,
    factory: // ...
    );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading