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

 

 

 

posted @   程序原快递  阅读(1038)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
点击右上角即可分享
微信分享提示