.ner CoreWebApi限流

本文介绍了如何在ASP.NET Core应用中通过AspNetCoreRateLimit库来限制API的访问频率,保护系统免受频繁请求的冲击。配置包括启用端点限流、设置响应内容和规则,并展示了在Startup类中添加依赖注入以及在Main方法中进行种子数据初始化的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 AspNetCoreRateLimit实现

Appsetting 中设置

  "IpRateLimiting": {
    "EnableEndpointRateLimiting": true,
    "StackBlockedRequests": false,
    "RealIpHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "HttpStatusCode": 429,
    "QuotaExceededResponse": {
      "Content": "{{\"code\":429,\"msg\":\"访问过于频繁,请稍后重试\",\"data\":null}}",
      "ContentType": "application/json; charset=utf-8",
      "StatusCode": 429
    },
    "GeneralRules": [
      {
        "Endpoint": "*:/api/v1/Address/CreatOrder",
        "Period": "1m",
        "Limit": 1
      },
      {
        "Endpoint": "*:/api/values/",
        "Period": "1s",
        "Limit": 10
      }
      ]

Startup ConfigureServices中依赖注入


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

            services.AddOptions();

            // 存储IP计数器及配置规则

            services.AddMemoryCache();
            services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();
            services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
          
            services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();

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

            services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

Configure 中注册服务

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseIpRateLimiting();
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

Main 中使用种子

   public static async Task Main(string[] args)
        {

           IHost webHost = CreateHostBuilder(args).Build();
            using (var scope = webHost.Services.CreateScope())
            {
                // get the IpPolicyStore instance
                var ipPolicyStore = scope.ServiceProvider.GetRequiredService<IIpPolicyStore>();

                // seed IP data from appsettings
                await ipPolicyStore.SeedAsync();
            }

            await webHost.RunAsync();

        }

使用效果

在这里插入图片描述
在这里插入图片描述