request limit net core
1.0.0
报告在任何系统中都很常见,其中一些可能非常沉重。因此,在这种情况下,该应用程序在报告的生成过程中可能会降级,从而影响其他用户。但是,我们如何避免这种情况呢?第一个想法是挡住底部,对吗?嗯,但是很容易入侵,用户可以只编辑HTML道具并再次启用它。因此,最好的选择是使用某些请求限制控制策略在服务器端阻止它。
AspNetCoreRateLimit是一个可以帮助我们进行申请控制的库。您可以定义规则以确定客户可以在一段时间内调用资源的次数。
但是它如何工作?
ASPNETCORERATELIMIT使用MemoryCache解决方案来保存有关客户端请求的信息。例如,客户只能以5秒的间隔对特定端点提出10个请求。因此,每个请求将保存在内存缓存中,如果客户端超过此限制,则应用程序将停止请求并返回HTTP错误状态。
首先,我们需要安装库AspnetCorerateLimit
配置AspnetCorerateLimit的最佳选择是在AppSettings.json中定义所有信息。因此,我们将创建一个这样的块:
"IpRateLimiting": {
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": false,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"HttpStatusCode": 429,
"GeneralRules": [
{
"Endpoint": "*/api/test",
"Period": "2s", //interval
"Limit": 2 //limit of request in the interval
}
]
},
通过配置规则,我们需要在Startup.cs中添加几行:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
//AspNetCoreRateLimit uses MemoryCache to control the numbers of requests
services.AddMemoryCache();
//Adding AspNetCoreRateLimit rules
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
//Adding the store
services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
//Adding the request counter
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
services.AddHttpContextAccessor();
services.AddControllers();
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "RequestLimit", Version = "v1" });
});
}
最后一步是激活服务:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "RequestLimit v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseIpRateLimiting() //Adding this block;
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
它已经完成了,现在我们的API具有请求控件。您可以自定义配置以遵循具体规则,所有选项均在此处列出:https://github.com/stefanprodan/aspnetcoreratelimit