ASP.NET Core 请求限速的ActionFilter

文章目录


前言

以下是一个基于内存缓存实现的自定义限流Action Filter。

一、实现步骤

1)创建自定义Action Filter

示例1:

  1. MyRateLimitAttribute.cs

    bash 复制代码
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    using Microsoft.Extensions.Caching.Memory;
    
     public class MyRateLimitAttribute : TypeFilterAttribute
     {
         public MyRateLimitAttribute() 
             :base(typeof(MyRateLimitFilter))
         {
         }
         public class MyRateLimitFilter : IAsyncActionFilter
         {
             private readonly IMemoryCache _memoryCache;
    
             public MyRateLimitFilter(IMemoryCache memoryCache)
             {
                 _memoryCache = memoryCache;
             }
    
             public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
             {
                 string ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
                 if (string.IsNullOrEmpty(ip))
                 {
                     context.Result = new BadRequestObjectResult("Invalid Client IP");
                     return;
                 }
                 string cacheKey = $"MyRateLimit_{ip}";
                 _memoryCache.TryGetValue<long?>(cacheKey, out long? lastVisit);
                 if (lastVisit == null || Environment.TickCount64 - lastVisit > 1000)
                 {
                     _memoryCache.Set(cacheKey, Environment.TickCount64, TimeSpan.FromSeconds(10));
                     await next();
                 }
                 else
                 {
                     context.Result = new ObjectResult("访问太频繁") { StatusCode=429};                    
                 }
             }
         }
     }

示例2:

  1. RateLimitAttribute.cs

    bash 复制代码
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    using Microsoft.Extensions.Caching.Memory;
    
    public class RateLimitAttribute : TypeFilterAttribute
    {
        public RateLimitAttribute(int maxRequests,int secondsWindow) 
            : base(typeof(RateLimitFilter))
        {
            Arguments = new object[] { maxRequests,secondsWindow};
        }
    
        public class RateLimitFilter : IAsyncActionFilter
        {
            private readonly IMemoryCache _memoryCache;
            private readonly int _maxRequests;
            private readonly int _secondsWindow;
    
            public RateLimitFilter(IMemoryCache memoryCache, int maxRequests, int secondsWindow)
            {
                _memoryCache = memoryCache;
                _maxRequests = maxRequests;
                _secondsWindow = secondsWindow;
            }
    
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                var ip=context.HttpContext.Connection.RemoteIpAddress?.ToString();
                if (string.IsNullOrEmpty(ip))
                {
                    context.Result = new BadRequestObjectResult("Invalid client IP");
                    return;
                }
                var cacheKey = $"RateLimit_{ip}";
                var windowStart = DateTime.UtcNow.AddSeconds(-DateTime.UtcNow.Second % _secondsWindow);
                if (!_memoryCache.TryGetValue(cacheKey, out RateLimitCounter counter) ||
                    windowStart > counter.WindowStart)
                {
                    counter = new RateLimitCounter
                    {
                        Count = 1,
                        WindowStart = windowStart,
                    };
                }
                else
                {
                    counter.Count++;
                }
    
                if (counter.Count > _maxRequests)
                {
                    context.Result = new ObjectResult("Too many requests")
                    {
                        StatusCode = 429
                    };
                    return;
                }
                _memoryCache.Set(cacheKey, counter, counter.WindowStart.AddSeconds(_secondsWindow));
                await next();
            }
            private class RateLimitCounter
            {
                public int Count { get; set; }
                public DateTime WindowStart { get; set; }
            }
        }
    }

2)注册服务

  1. 内存缓存服务

    bash 复制代码
    builder.Services.AddMemoryCache();

3)使用

  1. 示例:

    bash 复制代码
    [HttpGet]
    //[RateLimit(maxRequests: 5, secondsWindow: 60)] // 每分钟最多5次请求
    [MyRateLimit]
    public async Task<ActionResult<Book>> GetAllBookAsync()
    {
        var res=await _bookRepository.GetAllAsync();
        return Ok(res);
    }

二、实现说明

  1. 使用IP地址识别客户端(需考虑代理场景)
  2. 基于固定时间窗口算法(每分钟/小时重置计数器)(示例2)
  3. 使用IMemoryCache存储计数器
  4. 返回429状态码(Too Many Requests)时阻止请求

总结

  1. 内存缓存方案仅适用于单实例部署
  2. 高并发场景建议使用Interlocked类处理计数器原子操作
  3. 生产环境推荐使用分布式缓存(如Redis
  4. 建议使用成熟的限流库(如AspNetCoreRateLimit
相关推荐
IT_10243 小时前
Spring Boot项目开发实战销售管理系统——系统设计!
大数据·spring boot·后端
ai小鬼头4 小时前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
Touper.4 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
一只叫煤球的猫5 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
一只鹿鹿鹿5 小时前
信息化项目验收,软件工程评审和检查表单
大数据·人工智能·后端·智慧城市·软件工程
专注VB编程开发20年5 小时前
开机自动后台运行,在Windows服务中托管ASP.NET Core
windows·后端·asp.net
程序员岳焱5 小时前
Java 与 MySQL 性能优化:MySQL全文检索查询优化实践
后端·mysql·性能优化
一只叫煤球的猫6 小时前
手撕@Transactional!别再问事务为什么失效了!Spring-tx源码全面解析!
后端·spring·面试
旷世奇才李先生6 小时前
Ruby 安装使用教程
开发语言·后端·ruby
沃夫上校9 小时前
Feign调Post接口异常:Incomplete output stream
java·后端·微服务