使用 AspNetCoreRateLimit实现
Appsetting 中设置
"IpRateLimiting": {
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": false,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"HttpStatusCode": 429,
"QuotaExceededResponse": {
"Content": "{{\"code\":429,\"msg\":\"访问过于频繁,请稍后重试\",\"data\":null}}",
"ContentType": "application/json; charset=utf-8",
"StatusCode": 429
},
"GeneralRules": [
{
"Endpoint": "*:/api/v1/Address/CreatOrder",
"Period": "1m",
"Limit": 1
},
{
"Endpoint": "*:/api/values/",
"Period": "1s",
"Limit": 10
}
]
Startup ConfigureServices中依赖注入
// 需要从appsettings.json中加载配置
services.AddOptions();
// 存储IP计数器及配置规则
services.AddMemoryCache();
services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
Configure 中注册服务
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIpRateLimiting();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Main 中使用种子
public static async Task Main(string[] args)
{
IHost webHost = CreateHostBuilder(args).Build();
using (var scope = webHost.Services.CreateScope())
{
// get the IpPolicyStore instance
var ipPolicyStore = scope.ServiceProvider.GetRequiredService<IIpPolicyStore>();
// seed IP data from appsettings
await ipPolicyStore.SeedAsync();
}
await webHost.RunAsync();
}
使用效果