AspNetCoreRateLimit 是一种 ASP.NET Core 速率限制解决方案,旨在根据 IP 地址或客户端 ID 控制客户端可以向 Web API 或 MVC 应用发出的请求速率。AspNetCoreRateLimit 包包含一个 IpRateLimitMiddleware 和一个 ClientRateLimitMiddleware,每个中间件您可以针对不同的场景设置多个限制,例如允许 IP 或客户端在时间间隔内(如每秒、15 分钟等)进行最大调用次数。您可以定义这些限制以处理对 API 发出的所有请求,也可以将限制范围限定为每个 API URL 或 HTTP 谓词和路径。
AspNetCoreRateLimit项目地址:https://github.com/stefanprodan/AspNetCoreRateLimit
项目是支持.NET 7的,本文以.NET 7的WEBAPI为例
Install-Package AspNetCoreRateLimit
Install-Package AspNetCoreRateLimit.Redis
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"IpRateLimiting": {
"EnableEndpointRateLimiting": false,
"StackBlockedRequests": false,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"HttpStatusCode": 429,
"IpWhitelist": [ "127.0.0.1", "::1/10", "192.168.0.0/24" ],
"EndpointWhitelist": [ "get:/api/license", "*:/api/status" ],
"ClientWhitelist": [ "dev-id-1", "dev-id-2" ],
"GeneralRules": [
{
"Endpoint": "*",
"Period": "1s",
"Limit": 2
},
{
"Endpoint": "*",
"Period": "15m",
"Limit": 100
},
{
"Endpoint": "*",
"Period": "12h",
"Limit": 1000
},
{
"Endpoint": "*",
"Period": "7d",
"Limit": 10000
}
]
},
"IpRateLimitPolicies": {
"IpRules": [
{
"Ip": "84.247.85.224",
"Rules": [
{
"Endpoint": "*",
"Period": "1s",
"Limit": 10
},
{
"Endpoint": "*",
"Period": "15m",
"Limit": 200
}
]
},
{
"Ip": "192.168.3.22/25",
"Rules": [
{
"Endpoint": "*",
"Period": "1s",
"Limit": 5
},
{
"Endpoint": "*",
"Period": "15m",
"Limit": 150
},
{
"Endpoint": "*",
"Period": "12h",
"Limit": 500
}
]
}
]
}
}
using AspNetCoreRateLimit;
using Microsoft.Extensions.Configuration;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
#region 注入限流
//需要从appsettings.json加载配置
builder.Services.AddOptions();
//需要存储速率限制计数器和ip规则
builder.Services.AddMemoryCache();
//从appsettings.json加载常规配置
builder.Services.Configure<IpRateLimitOptions>(builder.Configuration.GetSection("IpRateLimiting"));
//从appsettings.json加载ip规则
builder.Services.Configure<IpRateLimitPolicies>(builder.Configuration.GetSection("IpRateLimitPolicies"));
// 注入计数器和规则存储
builder.Services.AddInMemoryRateLimiting();
//services.AddDistributedRateLimiting<AsyncKeyLockProcessingStrategy>();
//services.AddDistributedRateLimiting<RedisProcessingStrategy>();
//services.AddRedisRateLimiting();
builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
#endregion
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
#region 使用限流
app.UseIpRateLimiting();
#endregion
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
如果你对应用程序进行负载平衡,你需要将IDistributedCache与Redis或SQLServer一起使用,以便所有kestrel实例都具有相同的速率限制存储。您应该像这样注入分布式存储,而不是内存存储:
services.AddSingleton<IIpPolicyStore, DistributedCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore,DistributedCacheRateLimitCounterStore>();
IpRateLimiting的主要配置说明:
IpRateLimitPolicies的主要配置说明:
这边只是讲解了基本用法,更多详细用法可以参考官网