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