ASP.NET Core 8 Web API -

Rate Limiting

Rate limiting is an essential feature to control the number of requests a user can make to an API within a certain time period. This prevents abuse and ensures fair usage of resources. ASP.NET Core 8 provides several ways to implement rate limiting. Below is a comprehensive guide to implementing rate limiting in an ASP.NET Core 8 Web API.


1. Why Rate Limiting?


2. Common Rate Limiting Strategies


3. Implementing Rate Limiting in ASP.NET Core 8 Web API

Rate limiting can be implemented using custom middleware, built-in middleware, or third-party libraries. Below are examples for each approach.


3.1 Using Custom Middleware RateLimitingMiddleware.cs:
        
            public class RateLimitingMiddleware
{
    private readonly RequestDelegate _next;
    private static readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());

    public RateLimitingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var ipAddress = context.Connection.RemoteIpAddress?.ToString();
        var endpoint = context.Request.Path;

        if (string.IsNullOrEmpty(ipAddress))
        {
            await _next(context);
            return;
        }

        var cacheKey = $"{ipAddress}:{endpoint}";
        var requestCount = _cache.Get<int>(cacheKey);

        if (requestCount >= 100)
        {
            context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
            await context.Response.WriteAsync("Rate limit exceeded. Try again later.");
            return;
        }

        _cache.Set(cacheKey, requestCount + 1, TimeSpan.FromMinutes(1));
        await _next(context);
    }
}
        
    


RateLimitingMiddlewareExtensions.cs:
        
            public static class RateLimitingMiddlewareExtensions
{
    public static IApplicationBuilder UseRateLimiting(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<RateLimitingMiddleware>();
    }
}
        
    


Program.cs:
        
            var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllers();

var app = builder.Build();

// Use the rate limiting middleware
app.UseRateLimiting();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
        
    

3.2 Using ASP.NET Core Rate Limiting Middleware Startup.cs:
        
            public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddRateLimiting(options =>
        {
            options.GlobalLimit = 100;
            options.Period = TimeSpan.FromMinutes(1);
            options.LimitExceededMessage = "Rate limit exceeded. Try again later.";
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseRateLimiting();

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


Program.cs:
        
            var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddRateLimiting(options =>
{
    options.GlobalLimit = 100;
    options.Period = TimeSpan.FromMinutes(1);
    options.LimitExceededMessage = "Rate limit exceeded. Try again later.";
});

var app = builder.Build();

app.UseRateLimiting();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
        
    

3.3 Using Third-Party Libraries

Third-party libraries like AspNetCoreRateLimit provide advanced features for rate limiting.

Install the library:
        
            // Install the library using the following command:
// dotnet add package AspNetCoreRateLimit
        
    


Program.cs:
        
            var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddMemoryCache();
builder.Services.Configure<IpRateLimitOptions>(options =>
{
    options.GeneralRules = new List<RateLimitRule>
    {
        new RateLimitRule
        {
            Endpoint = "*",
            Limit = 100,
            Period = "1m"
        }
    };
});

builder.Services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
builder.Services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
builder.Services.AddInMemoryRateLimiting();

var app = builder.Build();

app.UseIpRateLimiting();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
        
    


appsettings.json:
        
            {
  "IpRateLimiting": {
    "EnableEndpointRateLimiting": true,
    "StackBlockedRequests": false,
    "RealIpHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "HttpStatusCode": 429,
    "GeneralRules": [
      {
        "Endpoint": "*",
        "Period": "1m",
        "Limit": 100
      }
    ]
  }
}
        
    

4. Conclusion

Implementing rate limiting in ASP.NET Core 8 Web API can help you control the number of requests to your API and prevent abuse. You can use custom middleware, built-in rate limiting middleware, or third-party libraries like AspNetCoreRateLimit to achieve this. By configuring rate limiting appropriately, you can ensure fair usage and protect your API from being overwhelmed by too many requests.