为什么在 Asp.Net Core 使用此 AspNetCoreRateLimit 中间件时无法启动速率限制

Tom*_*yan 4 asp.net-core

有人可以告诉我我做错了什么吗...我正在使用这个中间件来限制客户端可以对我的端点进行的 API 调用的数量: https ://github.com/stefanprodan/AspNetCoreRateLimit/wiki/ IpRateLimit中间件

我无法启动此速率限制。这是我的 Startup.cs (相关部分):

public void ConfigureServices(IServiceCollection services)
{
    // needed to load configuration from appsettings.json
    services.AddOptions();

    // needed to store rate limit counters and ip rules
    services.AddMemoryCache();

    //load general configuration from appsettings.json
    services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));

    // inject counter and rules stores
    services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
    services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

    // https://github.com/aspnet/Hosting/issues/793
    // the IHttpContextAccessor service is not registered by default.
    // the clientId/clientIp resolvers use it.
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // configuration (resolvers, counter key builders)
    services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

    // Configure strongly-typed configuration settings objects
    var appSettingsSection = Configuration.GetSection("AppSettings");
    services.Configure<AppSettings>(appSettingsSection);
    var appSettings = appSettingsSection.Get<AppSettings>();

    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
            corsBuilder => corsBuilder.WithOrigins("*")
            .AllowAnyMethod()
            .AllowAnyHeader());
    });

    services.AddControllers();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
    // Ensure that the CORS call is before UseMvc
    app.UseCors("AllowSpecificOrigin");

    loggerFactory.AddLog4Net();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseIpRateLimiting();

    app.UseHttpsRedirection();

    app.UseRouting();

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

}
Run Code Online (Sandbox Code Playgroud)

我的 appsettings.json 文件:

"IpRateLimiting": {
      "EnableEndpointRateLimiting": true,
      "StackBlockedRequests": false,
      "RealIPHeader": "X-Real-IP",
      "ClientIdHeader": "X-ClientId",
      "HttpStatusCode": 429,
      "GeneralRules": [
        {
          "Endpoint": "*",
          "Period": "10s",
          "Limit": 1
        }
      ]
    }
Run Code Online (Sandbox Code Playgroud)

仅供参考,我已尝试将 EnableEndpointRateLimiting 设置为“true”和“false”,但都没有效果。

我的测试 API 调用都在进行……当我预计会受到限制时!

Tom*_*yan 5

事实证明,这对我来说是一个非常愚蠢的错误。我将 IpRateLimiting 会话嵌套在 appsettings.json 文件的“AppSettings”部分中,而本应在根级别指定它。

  • 您应该接受这个作为已接受的答案,看看您是如何回答这个问题的:-) (2认同)