CORE API 限流,防止,链接数过多而崩溃。

今天有个项目,使用的是EF core API 跨域接口。但是遇到的问题就是发布到公司服务器后,外网访问率低的情况正常。访问过多,则会直接导致IIS应用程序池对应程序崩溃,停止运行。

1、程序限流

      1.1、NuGet下载引用 AspNetCoreRateLimit

      1.2、startup中添加配置

               

复制代码
 1 #region IP限流配置
 2 
 3             // 存储IP计数器及配置规则
 4             services.AddMemoryCache();
 5             // 配置
 6             services.Configure<IpRateLimitOptions>(options =>
 7             {
 8                 //options.EnableEndpointRateLimiting = true; // true,意思是IP限制会应用于单个配置的Endpoint上,false,只能限制所有接口Endpoint只能为*
 9                 options.HttpStatusCode = 429; // 触发限制之后给客户端返回的HTTP状态码
10                 options.RealIpHeader = "X-Real-IP";
11                 options.ClientIdHeader = "X-ClientId";
12                 options.QuotaExceededResponse = new QuotaExceededResponse // 触发限制之后给客户端返回的数据
13                 {
14                     Content = "{{\"code\":-1,\"msg\":\"访问过于频繁,请稍后重试\"}}",
15                     ContentType = "application/json",
16                     StatusCode = 429
17                 };
18                 // 限制规则
19                 options.GeneralRules = new List<RateLimitRule>
20                 {
21                     new RateLimitRule
22                     {
23                         //Endpoint = "*:/signtoken",// 正则匹配规则,只针对签发token接口
24                         Endpoint = "*",
25                         Period = "1s",// 周期 s秒 m分钟 h时 d天
26                         Limit = 10,// 次数
27                     }
28                 };
29             });
30 
31             // 注入计数器和规则存储
32             services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
33             services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
34             // the clientId/clientIp resolvers use it.
35             services.AddHttpContextAccessor();
36             // 配置(计数器密钥生成器)
37             services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
38 
39             #endregion
ConfigureServices配置
复制代码
1 // 启用限流,放在app.UseRouting();之前
2 app.UseIpRateLimiting();
Configure配置

 

 2、IIS配置

 

 

 

 

   

posted on   木乃伊人  阅读(349)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示