为什么当使用此AspNetCoreRateLimit中间件作为Asp.Net Core时,我无法获得启动的速率限制

问题描述 投票:0回答:1

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

我无法获得此速率限制。这是我的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();
    });

}

以及我的appsettings.json文件:

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

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

我希望受到限制时,我的测试API调用将全部通过...

asp.net-core
1个回答
0
投票

这对我来说是一个非常愚蠢的错误。我应该在根目录级别上将IpRateLimiting会话嵌套在我的appsettings.json文件中的“ AppSettings”部分中。

© www.soinside.com 2019 - 2024. All rights reserved.