Location>code7788 >text

How to implement rate limiting in Core?

Popularity:577 ℃/2025-01-15 10:02:57

Implementing rate limiting (Rate Limiting) middleware in Core can help you control the frequency of client requests to the API and prevent abuse and overload. Rate limiting is typically used to protect server resources and ensure service stability and availability.

Core itself does not have built-in rate limiting middleware, but you can implement rate limiting through custom middleware or using third-party libraries. Here are a few common ways to implement rate limiting:


1. Implement rate limiting using custom middleware

You can implement rate limiting through custom middleware. Here is a simple implementation example:

1.1 Implement rate limiting middleware

 _rateLimiters;

 Public RateLimitingMiddleware(RequestDelegate next, int maxRequests)
 {
 ​ ​ _next = next;
 ​ ​ _maxRequests = maxRequests;
 ​ ​ _rateLimiters = new ConcurrentDictionary();
 }

 Public async Task InvokeAsync(HttpContext context)
 {
 ​​​​//Get the client’s unique identifier (such as IP address)
       var  clientId  =  ();

              // Get or create a rate limiter
       var  rateLimiter = _rateLimiters.GetOrAdd(clientId, _ => new RateLimiter(_maxRequests));

 if (())
                       
                                                                                                                                                                          await _next (context));
 }
           else
                       
                                                 = StatusCodes.Status429TooManyRequests;
 await ("Too many requests. Please try again later.");
 }
 }
 }

 public class RateLimiter
 {
 Private readonly int _maxRequests;
 Private int _requestCount;
 Private DateTime _windowStart;

 Public RateLimiter(int maxRequests)
 {
 ​ ​ _maxRequests = maxRequests;
 ​ ​ _requestCount = 0;
 ​ ​ _windowStart = ;
 }

 Public bool AllowRequest()
 {
         var now = ;

              // If the current time window has expired, reset the counter
 If ((now - _windowStart).TotalSeconds > 60)
                       
 ​​​​​​_requestCount = 0;
             _windowStart = now;
 }

               // Check whether the request exceeds the limit
 If (_requestCount < _maxRequests)
                       
 ​​​​​​_requestCount++;
                return true;
 }

                         return false;
 }
 }

1.2 Registration middleware

existRegister middleware in:

(10); // Maximum 10 requests per minute

 ();

 (endpoints =>
                                     
                                                 ();
                 });
 }

2. Implementing rate limiting using third-party libraries

If you don't want to implement the rate limiting logic yourself, you can use some ready-made third-party libraries, such as:

2.1 AspNetCoreRateLimit

AspNetCoreRateLimit is a popular Core rate limiting library that supports IP address, client ID, and endpoint level rate limiting.

Install

Install via NuGet:

dotnet add package AspNetCoreRateLimit
Configuration

existConfigure rate limit in:

(("IpRateLimiting"));
 ();
 ();
 ();
 ();
 ();
 }

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
 ();

 ();

 (endpoints =>
                                     
                                                 ();
                 });
 }
Configuration file

existAdd rate limit configuration in:

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

3. Implementing rate limiting using distributed cache

If your application is distributed (such as deployed on Kubernetes or multiple servers), you can use a distributed cache (such as Redis) to implement rate limiting.

3.1 Using Redis to implement rate limiting

You can use Redis to store per-client request counts. Here's a simple example:

using ;
 using ;
 using ;

 public class RedisRateLimitingMiddleware
 {
 Private readonly RequestDelegate _next;
 Private readonly int _maxRequests;
 Private readonly ConnectionMultiplexer _redis;

 Public RedisRateLimitingMiddleware(RequestDelegate next, int maxRequests, ConnectionMultiplexer redis)
 {
 ​ ​ _next = next;
 ​ ​ _maxRequests = maxRequests;
 ​ ​ _redis = redis;
 }

 Public async Task InvokeAsync(HttpContext context)
 {
       var  clientId  =  ();
       var db = _redis.GetDatabase();

       var key = $"rate_limit:{clientId}";
       var requestCount = await (key);

 If (requestCount == 1)
                       
                                                                                                     await (key, (1));
 }

 If (requestCount > _maxRequests)
                       
                                                 = StatusCodes.Status429TooManyRequests;
 await ("Too many requests. Please try again later.");
 }
           else
                       
                                                                                                                                                                          await _next (context));
 }
 }
 }

3.2 Registration middleware

existRegister middleware in:

(("localhost:6379"));
 }

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
 (10); // Maximum 10 requests per minute

 ();

 (endpoints =>
                                     
                                                 ();
                 });
 }

4. Summarize

There are several ways to implement rate limiting in Core:

  • Custom middleware: Suitable for simple scenarios, but you need to implement the logic yourself.
  • Third-party libraries: Such as AspNetCoreRateLimit, which provides more powerful functions and flexibility.
  • Distributed cache: Such as Redis, suitable for distributed environments.

Choose the right approach based on your needs to ensure your API is protected against abuse and overload.