Search code examples
c#asp.net-corerate-limiting

Rate limit policy settings is not applied using AspNetCoreRateLimit


I am using AspNetCoreRateLimit version 4.0.1 and I have done all the setup in .net core 6 web API. I can see rate limit is working when I send a call via Postman.

However, when I add IpRateLimitPolicies with specific IP address, the settings won't be applied. I use Postman and this time in the proxy I added the IP address to 127.0.0.1. I can see the IP hitting the API is set correctly when I use Request.HttpContext.Connection.RemoteIpAddress;

I registered them as follow in program.cs:

    _serviceCollection.AddOptions();
    _serviceCollection.AddMemoryCache();
    _serviceCollection.Configure<IpRateLimitOptions>(builder.Configuration.GetSection("IpRateLimiting"));
     _serviceCollection.Configure<IpRateLimitPolicies>(builder.Configuration.GetSection("IpRateLimitPolicies"));
     _serviceCollection.AddInMemoryRateLimiting();
     _serviceCollection.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
     _serviceCollection.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
     _serviceCollection.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
     _serviceCollection.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

Also added: app.UseIpRateLimiting();

My appsettings also looks like:

 {
  "IpRateLimiting": {
    "EnableEndpointRateLimiting": false,
    "StackBlockedRequests": false,
    "RealIPHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "IpWhitelist": [ ],
    "EndpointWhitelist": [],
    "ClientWhitelist": [],
    "HttpStatusCode": 429,
    "GeneralRules": [
      {
        "Endpoint": "*",
        "Period": "10s",
        "Limit": 1
      }
    ]
  },
  "IpRateLimitPolicies": {
    "IpRules": [
      {
        "Ip": "127.0.0.1",
        "Rules": [
          {
            "Endpoint": "*",
            "Period": "20s",
            "Limit": 2
          }
        ]
      }
    ]
  }

But apparently the settings under IpRateLimitPolicies won't be applied.

I wonder if I have missed anything here?


Solution

  • Apparently I have missed some configuration in program.cs or startup.cs:
    Rate limit policy settings is not applied using AspNetCoreRateLimit in .net core 6

    I have added the following in configure method because of using startup:

    var ipPolicyStore = app.ApplicationServices.GetRequiredService<IIpPolicyStore>(); 
    ipPolicyStore.SeedAsync().GetAwaiter().GetResult();