.Net Core使用AspNetCoreRateLimit实现限流

1.添加Nuget程序包

.Net Core使用AspNetCoreRateLimit实现限流

 

 

 2.在start up中进行配置【有两种模式可选 存储在redis中会哦这内存中】

// 需要从appsettings.json中加载配置

            services.AddOptions();

            // 存储IP计数器在内存中

            services.AddMemoryCache();
           //或者存储在redis中

  //services.AddDistributedRedisCache(options =>{

//options.Configuration = "119.45.138.19:6379,password=123456,connectTimeout=5000,syncTimeout=10000";

             //options.InstanceName = "WebRatelimit";
             //});


            services.Configure<IpRateLimitOptions>(Configuration.GetSection("RateLimitingConfig"));

            services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();

            services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
     
             services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  
             services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

3.在appsetting.json中配置相关参数

  "RateLimitingConfig": {
    //false则全局将应用限制,并且仅应用具有作为端点的规则* 。 true则限制将应用于每个端点
    "EnableEndpointRateLimiting": true,
    //false则拒绝的API调用不会添加到调用次数计数器上  
    "StackBlockedRequests": false,
    //获取用户端的真实IP
    "RealIpHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "HttpStatusCode": 200,
    "QuotaExceededResponse": {
      "Content": "{{\"code\":429,\"msg\":\"Visit too frequently, please try again later\",\"data\":null}}",
      "ContentType": "application/json",
      "StatusCode": 200
    },
   //ip白名单
    "IpWhitelist": [ "139.159.187.209" ],
    "EndpointWhitelist": [],
    "ClientWhitelist": [],
    "GeneralRules": [
      {
        "Endpoint": "*",
        "Period": "60s",
        "Limit": 0
      }
    ]
  }

4.启用配置

//位置放在控制器前面
app.UseIpRateLimiting();

 

.Net Core使用AspNetCoreRateLimit实现限流

上一篇:js获取地址栏参数


下一篇:vue JS获取当前时间并格式化 ( 前端小细节,大进步 )