AspNetCoreRateLimit接口访问限制中间件的使用

1、在接口项目nutget中找到AspNetCoreRateLimit组件

2、在appsettings.json中配置以下内容

"IpRateLimiting": {
    //当为True的时候 例如设置了5次每分钟访问限流,当你getData()5次过后禁止访问,但是还可以访问postData()5次,
    //总得来说是每个接口都有5次在这一分钟,互不干扰。"当为False的时候" "每个接口都加入计数,不管你访问哪个接口","只要在一分钟内累计够5次" "将禁止访问",
    "EnableEndpointRateLimiting": true,
    "StackBlockedRequests": false,
    "RealIpHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "IpWhitelist": null,
    "EndpointWhitelist": null,
    "HttpStatusCode": 429,
    "QuotaExceededResponse": {
      "Content": "{{ \"message\": \"Too many requests,Please try again in {2} second(s).\", \"code\": 429,\"data \":\"\"}}",
      "ContentType": "application/json"
    },
    "GeneralRules": [
      {
        "Endpoint": "*",
        "Period": "4s",
        "Limit": 1
      }
    ]
  }

3、在Startup.cs中ConfigureServices方法中添加配置

    #region 限流配置
            //加载配置
            services.AddOptions();
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);//设置兼容性版本
            services.AddMemoryCache();
            //加载IpRateLimiting配置
            services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
            //注入计数器和规则存储
            services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
            services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
            //添加框架服务
            services.AddMvc();
            // clientId / clientIp解析器使用它。
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //配置(计数器密钥生成器)
            services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
            #endregion

4、在Startup.cs中Configure方法中注册使用中间件

app.UseIpRateLimiting();

注意,可以自定义中间件来指定返回的信息,即在appsettings.json中IpRateLimiting节点下面的QuotaExceededResponse信息,方法如下:

在项目中自定义添加一个IPLimitMiddleware类,然后继承IpRateLimitMiddleware类,重写ReturnQuotaExceededResponse方法,代码如下:

  public class IPLimitMiddleware : IpRateLimitMiddleware
    {
        private readonly IpRateLimitOptions _options;
        private readonly IIpPolicyStore _ipPolicyStore;

        public IPLimitMiddleware(RequestDelegate next, IOptions<IpRateLimitOptions> options, IRateLimitCounterStore counterStore, IIpPolicyStore policyStore, 
            IRateLimitConfiguration config, ILogger<IpRateLimitMiddleware> logger)
            : base(next, options, counterStore, policyStore, config, logger)
        {
            _options = options.Value;
            _ipPolicyStore = policyStore;
        }

        public override Task ReturnQuotaExceededResponse(HttpContext httpContext, RateLimitRule rule, string retryAfter)
        {
            var ip = httpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = httpContext.Connection.RemoteIpAddress.ToString();
            }
            httpContext.Response.ContentType = "application/json";
            return httpContext.Response.WriteAsync($"{{ \"Code\": 429,\"msg\": \"操作频率过快,要求是: 每{rule.Period}秒{rule.Limit}次,请在{retryAfter}秒后再试!\" }}");
        }
    }

小问题1:在appsettings.json中定义的中文信息,取出来之后如果出现了乱码,则可以通过notpad++ 将文件格式改为utf-8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值