当前位置:网站首页>. 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
边栏推荐
- In redis cluster, the master node fails, and the IP changes after the master-slave switch. The client does not need to deal with it
- Realize QQ login with PHP
- MYSQL05_ Ordr by sorting, limit grouping, group by grouping
- Two methods are used to solve the "maximum palindrome product" problem
- 基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目
- c#可变参数params的介绍
- Onenet connection process
- 利用栈的回溯来解决“文件的最长绝对路径”问题
- 类似Jira的十大项目管理软件
- C#中元组对象Tuple的使用
猜你喜欢

Er and eer models
![[new version release] componentone added Net 6 and blazor platform control support](/img/08/71e7328f685a5cdd584f1bfdce5f2a.png)
[new version release] componentone added Net 6 and blazor platform control support

AOT和单文件发布对程序性能的影响

Source Generator实战

Drawing polygons with < polygon / > circular array in SVG tag

ASP. Net 6 middleware series - execution sequence

The most easy to understand dependency injection and control inversion

腾讯视频涨价:一年多赚74亿!关注我领取腾讯VIP会员,周卡低至7元

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

Introduction and use of openfeign component
随机推荐
【鉴权/授权】自定义一个身份认证Handler
树莓派开发笔记(十二):入手研华ADVANTECH工控树莓派UNO-220套件(一):介绍和运行系统
Xamarin效果第二十二篇之录音效果
ASP. Net 6 middleware series - Custom middleware classes
Impact of AOT and single file release on program performance
Summary of interface automation interview questions for software testing
Fight leetcode again (290. Word law)
Source generator actual combat
AOT和单文件发布对程序性能的影响
The most detailed in the whole network, software testing measurement, how to optimize software testing cost and improve efficiency --- hot
LNMP MySQL allows remote access
2022年度Top9的任务管理系统
Recursion - outputs continuously increasing numbers
C# 读写二进制文件
Notes sur le développement de la tarte aux framboises (XII): commencer à étudier la suite UNO - 220 de la tarte aux framboises de contrôle industriel advantech (i): Introduction et fonctionnement du s
Systemctl start Prometheus + grafana environment
.NET点滴:说说Middleware构造中获取不到Scoped服务的问题
[new version release] componentone added Net 6 and blazor platform control support
MySQL port is occupied when building xampp
最通俗易懂的依赖注入之生命周期