asp .net core 中间件实现, 避免请求并发过高

1,直接上代码

  /// <summary>
  /// 10 秒内 同ip最多放100次
  /// </summary>
  public class RequestThrottlingMiddleware
  {
      private const int outtime = 10;
      private const int total = 100;

      private readonly RequestDelegate _next;
      private readonly IMemoryCache _cache;
      public RequestThrottlingMiddleware(RequestDelegate next, IMemoryCache cache)
      {
          _next = next;
          _cache = cache;
      }

      public async Task Invoke(HttpContext context)
      {
          var ipAddress = context.Connection.RemoteIpAddress.ToString();
            
          // 用于设置10秒时间窗口
          var timeWindow = TimeSpan.FromSeconds(outtime);
          var cacheKey = $"{ipAddress}_{DateTime.UtcNow.Ticks / timeWindow.Ticks}";

          if (_cache.TryGetValue(cacheKey, out int requestCount))
          {
              // 如果请求次数超过100次,可以将IP地址加入黑名单或执行其他操作
              if (requestCount > total)
              {
                  // 加入黑名单的逻辑
                  context.Response.StatusCode = 403; // Forbidden
                  await context.Response.WriteAsync("IP Address is blacklisted.请求太频繁了,休息一下发请求吧!");
              }
              else
              {
                  // 请求次数加一
                  _cache.Set(cacheKey, requestCount + 1, timeWindow);
                  await _next(context);
              }
          }
          else
          {
              // 如果IP地址不在缓存中,将其添加到缓存并设置请求次数为1
              _cache.Set(cacheKey, 1, timeWindow);
              await _next(context);
          }
      }
  }

2, 配置中间件

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
//...
     //过滤请求频繁的
     app.UseMiddleware<RequestThrottlingMiddleware>();
//...
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值