This is a RateLimit that works with ActionFilters! An approach designed to control the request rate for specific Action or Controller. The idea behind this solution is to solve the middleware problem because the Middlewares affects all requests, but with action filters you can limit some of the critical endpoints.
Rate Limit uses InMemory cache by default, but if you set up a Redis connection it will use Redis, it is recommended to use Redis for checking the rate limit in the distributed applications. By default it limits the IP address but you can set ClientId in request headers and the header name is configurable.
TargetFramework | Support |
---|---|
net6.0 | ✅ |
net5.0 | ✅ |
netcoreapp3.1 | ✅ |
netstandard2.1 | ✅ |
netstandard2.0 | ✅ |
You can add RateLimit in Startup like this:
using DotNet.RateLimiter;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRateLimitService(builder.Configuration);
You can see the Demo project to know how to use in all scenarios and also you can follow this article in Medium.
Use RateLimit without any parameters
[HttpGet("")]
[RateLimit(PeriodInSec = 60, Limit = 3)]
public IEnumerable<WeatherForecast> Get()
{
....
}
[HttpGet("by-route/{id}")]
[RateLimit(PeriodInSec = 60, Limit = 3, RouteParams = "id")]
public IEnumerable<WeatherForecast> Get(int id)
{
....
}
[HttpGet("by-query/{id}")]
[RateLimit(PeriodInSec = 60, Limit = 3, RouteParams = "id", QueryParams = "name,family")]
public IEnumerable<WeatherForecast> Get(int id, string name, [FromQuery] List<string> family)
{
....
}
//if Scope set to Controller to rate limit work on all actions no matter which actions call
//the default value is Action means this rate limit check for each action separately
[RateLimit(Limit = 3, PeriodInSec = 60, Scope = RateLimitScope.Controller)]
public class RateLimitOnAllController : ControllerBase
{ .... }
[RateLimit(Limit = 3, PeriodInSec = 60, Scope = RateLimitScope.Controller)]
public class RateLimitOnAllController : ControllerBase
{
[HttpGet("")]
[IgnoreRateLimit]//ignore rate limit for this action
public IEnumerable<WeatherForecast> Get()
{
....
}
}
RateLimitOption in appsettings.json
"RateLimitOption": {
"EnableRateLimit": true, //Optional: if set false rate limit will be disabled, default is true
"HttpStatusCode": 429, //Optional: default is 429
"ErrorMessage": "Rate limit Exceeded", //Optional: default is Rate limit Exceeded
"IpHeaderName": "X-Forwarded-For" //Optional: header name for get Ip address, default is X-Forwarded-For
"RedisConnection": "127.0.0.1:6379", //Optional
"IpWhiteList": ["::1"], //Optional
"ClientIdentifier": "X-Client-Id" ////Optional: for getting client id from request header if this present the rate limit will not use IP for limit requests
"ClientIdentifierWhiteList": ["test-client"] ////Optional
}