当前位置:网站首页>. 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
边栏推荐
- Opencv combines multiple pictures into video
- Yes Redis using distributed cache in NE6 webapi
- Assembly learning Chapter III of assembly language (Third Edition) written by Wang Shuang
- 樹莓派開發筆記(十二):入手研華ADVANTECH工控樹莓派UNO-220套件(一):介紹和運行系統
- C#语法糖空合并运算符【??】和空合并赋值运算符【 ??=】
- Laravel8- use JWT
- 一套关于 内存对齐 的C#面试题,做错的人很多!
- 再战leetcode (290.单词规律)
- C syntax pattern matching [switch expression]
- Xamarin effect Chapter 21 expandable floating operation button in GIS
猜你喜欢
TP5 customization in extend directory succeeded and failed. Return information
Blazor University (12)组件 — 组件生命周期
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (7)
Some problems encountered in setting Django pure interface, channel and MySQL on the pagoda panel
搭建XAMPP时mysql端口被占用
AspNetCore配置多环境log4net配置文件
Array and collection types passed by openfeign parameters
ASP.NET 6 中间件系列 - 自定义中间件类
[format] simple output (2)
Impact of AOT and single file release on program performance
随机推荐
[Euler plan question 13] sum of large numbers
求二叉树的叶子结点个数
Blazor University (12)组件 — 组件生命周期
准备一个月去参加ACM,是一种什么体验?
Due to 3 ²+ four ²= five ², Therefore, we call '3,4,5' as the number of Pythagorean shares, and find the array of all Pythagorean shares within n (including n).
树莓派开发笔记(十二):入手研华ADVANTECH工控树莓派UNO-220套件(一):介绍和运行系统
c#语法糖模式匹配【switch 表达式】
Summary of interface automation interview questions for software testing
建立与遍历二叉树
Dynamic sequence table + OJ
Laravel's own paging query
be based on. NETCORE development blog project starblog - (1) why do you need to write your own blog?
C#中切片语法糖的使用
中后二叉建树
The backtracking of stack is used to solve the problem of "the longest absolute path of file"
Golden nine silver ten interview season, you are welcome to take away the interview questions (with detailed answer analysis)
[new version release] componentone added Net 6 and blazor platform control support
Swap the left and right of each node in a binary tree
Tencent video price rise: earn more than 7.4 billion a year! Pay attention to me to receive Tencent VIP members, and the weekly card is as low as 7 yuan
Tips in MATLAB