当前位置:网站首页>. net core current limiting control - aspnetcoreratelimit
. net core current limiting control - aspnetcoreratelimit
2022-04-23 03:08:00 【Dotnet cross platform】
brief introduction
AspNetCoreRateLimit yes ASP.NET Core rate limiting framework , Can be right WebApi,Mvc Control current limiting in the system ,AspNetCoreRateLimit Package contains IpRateLimit Middleware and ClientRateLimit middleware , Each middleware can set multiple limits for different scenarios , The author of the framework is stefanprodan, project nuget The address is https://github.com/stefanprodan/AspNetCoreRateLimit.
IpRateLimitMiddleware(Github: AspNetCoreRateLimit) yes ASPNETCore A current limiting middleware , Used to control client calls API Frequency of , If the client accesses the server frequently , You can limit its frequency , Reduced pressure to access the server side . Or if a crawler is crawling for key data , You can also limit a certain / some API Or some IP Number of calls per day , This limits his climbing speed .
Usage method
NuGet install :
Install-Package AspNetCoreRateLimit
Install-Package AspNetCoreRateLimit.Redis
Startup.cs Code :
public void ConfigureServices(IServiceCollection services)
{
// needed to load configuration from appsettings.json
services.AddOptions();
// needed to store rate limit counters and ip rules
services.AddMemoryCache();
//load general configuration from appsettings.json
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
//load ip rules from appsettings.json
services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));
// inject counter and rules stores
services.AddInMemoryRateLimiting();
//services.AddDistributedRateLimiting<AsyncKeyLockProcessingStrategy>();
//services.AddDistributedRateLimiting<RedisProcessingStrategy>();
//services.AddRedisRateLimiting();
// Add framework services.
services.AddMvc();
// configuration (resolvers, counter key builders)
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseIpRateLimiting();
app.UseMvc();
}
You should register the middleware before registering any other components .
If you load balance your application , You need to IDistributedCache And Redis or SQLServer Use it together , So that all kestrel All instances have the same rate limit storage . You should inject distributed storage like this , Instead of memory storage :
// inject counter and rules distributed cache stores
services.AddSingleton<IIpPolicyStore, DistributedCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore,DistributedCacheRateLimitCounterStore>();
Configuration and general rules application settings appsettings.json::
"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
}
]
}
If EnableEndpointRateLimiting Set to false, Then the limit will be applied globally , And only as endpoint* The rules of will apply . for example , If set per second 5 Limit of calls , Then for any HTTP Calls are counted against this limit .
If EnableEndpointRateLimiting Set to true, Then the restriction will apply to each endpoint , Such as {HTTP\u Verb}{PATH}. for example , If *:/api/values Set per second 5 Limit of calls , The client can call... Every second 5 Time GET/api/values, But you can also call 5 Time PUT/api/values.
If StackBlockedRequests Set to false, The rejected call will not be added to the throttle counter . If a client sends messages every second 3 A request , And you have set the limit to one call per second , So other restrictions ( Such as counter per minute or per day ) Only the first call that is not blocked will be recorded . If you want to reject a request, add other restrictions , You have to StackBlockedRequests Set to true.
When Kestrel When the server is behind the reverse proxy ,RealiPeader Used to extract client IP, If the proxy uses a different header , be X-Real-IP Use this option to set .
ClientHeader The client used to extract the whitelist id. If there is a client in this header id, And with ClientWhitelist Match the values specified in , The rate limit is not applied .
"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
}
]
}
]
}
IP Fields support IP v4 and v6 Value and range of , Such as “192.168.0.0/24”、“fe80::/10” or “192.168.0.0-192.168.0.255”.
版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230301333375.html
边栏推荐
- Establishing and traversing binary tree
- C# 11 对 ref 和 struct 的改进
- Load view Caton
- Impact of AOT and single file release on program performance
- Opencv combines multiple pictures into video
- [ncnn] - the meaning of - 23300 in param
- 编码电机PID调试(速度环|位置环|跟随)
- Openfeign service call
- Recommend reading | share the trader's book list and ask famous experts for trading advice. The trading is wonderful
- [new version release] componentone added Net 6 and blazor platform control support
猜你喜欢

荐读 | 分享交易员的书单,向名家请教交易之道,交易精彩无比

Laravel8- use JWT

ASP.NET 6 中间件系列 - 条件中间件

Use of slice grammar sugar in C #

Tencent video VIP member, weekly card special price of 9 yuan! Tencent official direct charging, members take effect immediately!

最通俗易懂的依赖注入与控制反转

C read / write binary file

准备一个月去参加ACM,是一种什么体验?

基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客?

2022A特种设备相关管理(电梯)上岗证题库及模拟考试
随机推荐
Development notes of raspberry pie (12): start Advantech industrial control raspberry pie uno-220 Kit (I): introduction and operation of the system
2022G2电站锅炉司炉考试题库及在线模拟考试
Swap the left and right of each node in a binary tree
准备一个月去参加ACM,是一种什么体验?
C# 读写二进制文件
.NET点滴:说说Middleware构造中获取不到Scoped服务的问题
How does Microsoft solve the problem of multiple PC programs
C syntax pattern matching [switch expression]
FileNotFoundError: [Errno 2] No such file or directory
使用栈来解决”迷你语法分析器“的问题
Source code interpretation of Flink index parameters (read quantity, sent quantity, sent bytes, received bytes, etc.)
Using stack to solve the problem of "mini parser"
微软是如何解决 PC 端程序多开问题的——内部实现
The most easy to understand dependency injection and control inversion
MAUI初体验:爽
最通俗易懂的依赖注入之生命周期
Opencv combines multiple pictures into video
C language to achieve address book - (static version)
Mise en service PID du moteur de codage (anneau de vitesse | anneau de position | suivant)
【鉴权/授权】自定义一个身份认证Handler