.NET core 6 add rate limit for calling API

.NET

Here are instructions of configuring a .NET core web api project to limit the number of calls to endpoints

First, install the package: AspNetCoreRateLimit

Add to the services section:


 services.AddOptions();
 services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
 services.AddMemoryCache();
 services.AddInMemoryRateLimiting();
 services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

Add the middleware:


app.UseIpRateLimiting();

Add to appsettings.json


"IpRateLimiting": {
    "EnableEndpointRateLimiting": true,
    "StackBlockedRequests": false,
    "RealIpHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "HttpStatusCode": 429,
    "GeneralRules": [
      {
        "Endpoint": "post:/auth/*",
        "Period": "10s",
        "Limit": 5
      }
    ]
  }

More information can be found here: https://github.com/stefanprodan/AspNetCoreRateLimit/wiki/IpRateLimitMiddleware#setup

Post a Comment

Previous Post Next Post