Asp.net rate limiting

As the title says, tried to rate limit api (for each IP, instead of global, to not cause issues), but it doesn't seem to work. Current code from Program.cs
using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy("fixed", httpContext => RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpContext.Connection.RemoteIpAddress?.ToString(),
factory: partition => new FixedWindowRateLimiterOptions
{
PermitLimit = 1,
Window = TimeSpan.FromSeconds(10)
}));
});

var app = builder.Build();

app.UseRateLimiter();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

app.Run();
using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy("fixed", httpContext => RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpContext.Connection.RemoteIpAddress?.ToString(),
factory: partition => new FixedWindowRateLimiterOptions
{
PermitLimit = 1,
Window = TimeSpan.FromSeconds(10)
}));
});

var app = builder.Build();

app.UseRateLimiter();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

app.Run();
3 Replies
With Blue Horns
With Blue HornsOP14mo ago
I think I may need to add something in controller too
Unknown User
Unknown User14mo ago
Message Not Public
Sign In & Join Server To View
With Blue Horns
With Blue HornsOP14mo ago
Such as this?
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;

[ApiController]
[Route("api/[controller]")]
public class CodeRedemption : ControllerBase
{
[HttpGet]
[EnableRateLimiting("fixed")]
public async Task<ActionResult<string>> GetString([FromQuery] string input)
{

}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;

[ApiController]
[Route("api/[controller]")]
public class CodeRedemption : ControllerBase
{
[HttpGet]
[EnableRateLimiting("fixed")]
public async Task<ActionResult<string>> GetString([FromQuery] string input)
{

}
}
Closed since found a workaround

Did you find this page helpful?