Search code examples
c#.netasp.net-coreasp.net-core-webapirate-limiting

.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

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: // ...
        );