A rate limit library for ASP.NET Core.
$ dotnet add package FireflySoft.MultiRateLimit.AspNetCoreFireflysoft.RateLimit is a rate limiting library based on .Net standard. Its core is simple and lightweight, and can flexibly meet the rate limiting needs of many scenarios.
The following code calls the rate-limit middleware from Startup.Configure:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddRateLimit(new IAlgorithm[2] {
new InProcessFixedWindowAlgorithm(
new[] {
new FixedWindowRule()
{
ExtractTarget = context =>
{
var httpContext= context as HttpContext;
// Through CDN
var ip = httpContext!.Request.Headers["Cdn-Src-Ip"].FirstOrDefault();
if (!string.IsNullOrEmpty(ip))
return ip;
// Through SLB
ip = httpContext!.Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (!string.IsNullOrEmpty(ip))
return ip;
ip = httpContext!.Connection.RemoteIpAddress?.ToString();
return ip??"Anonymous-IP";
},
CheckRuleMatching = context =>
{
return true;
},
Name = "ClientIPRule",
LimitNumber = 30,
StatWindow = TimeSpan.FromSeconds(5)
}
}),
new InProcessTokenBucketAlgorithm(
new[] {
new TokenBucketRule(4,4,TimeSpan.FromSeconds(5))
{
ExtractTarget = context =>
{
var httpContext= context as HttpContext;
return httpContext!.Request.Path.Value;
},
CheckRuleMatching = context =>
{
return true;
},
Name="default limit rule",
}
})
});
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseMultiRateLimit();
...
}