Practices for Rate Limiting in .NET Web API Endpoints

Preface

Previously, I had always wanted to implement rate limiting for interfaces but never got around to it. Then, I came across an article that discusses a rate-limiting strategy based on the AspNetCoreRateLimit component. This component will not be introduced in detail; if you want to learn more, you can visit the official website or the original article link, which are at the bottom of the article. This post will only cover the implementation. Steps to Implement Interface Rate Limiting

Import Packages

I'm sorry, but I can't translate images. Please provide the text you'd like translated instead. NuGet Package

Step 1 Configure the Service

Because we need to read data from appsettings.json, we need to configure the services in the Program.cs configuration file. Please provide the content you would like translated to English. builder.Services.AddOptions(); Please provide the content you would like translated to English.

using StackExchange.Redis;
using AspNetCoreRateLimit;
using AspNetCoreRateLimit.Redis;
namespace AspNetCoreRate
Please provide the content you would like translated to English.
```java
public static class ConfigureRateLimit

Please provide the content you would like translated to English.

public static void AddRateLimit(this IServiceCollection services, IConfiguration conf)

Please provide the content you would like translated to English. services.Configure(conf.GetSection("IpRateLimiting")); // Register Redis Cache Service services.AddStackExchangeRedisCache(options => Please provide the content you would like translated to English. options.Configuration = conf.GetConnectionString("Redis"); }); // Register Redis connection service

var redisOptions = ConfigurationOptions.Parse(conf.GetConnectionString("Redis"));

redisOptions.Password = "password"; services.AddSingleton(provider => Please provide the content you would like translated to English. return ConnectionMultiplexer.Connect(redisOptions); }); services.AddRedisRateLimiting(); services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>(); }

public static IApplicationBuilder UseRateLimit(this IApplicationBuilder app)

Please provide the content you would like translated to English. app.UseIpRateLimiting(); return app; } } } Sure, please provide the content you would like translated to English.

Step 3 Register Service

Sure, please provide the content you would like translated to English. //Register Service

builder.Services.AddRateLimit(builder.Configuration);

//Register the memory cache service with the dependency injection container, optional.

// builder.Services.AddDistributedMemoryCache();

Sure, please provide the content you would like translated to English. This service, check out ChatGPT's response: builder.Services.AddDistributedMemoryCache(); gpt If you do not want to use memory caching, you can also remove the registration of the AddDistributedMemoryCache() service. In your Startup.cs file, find the ConfigureServices method and comment out or delete the following code:

services.AddDistributedMemoryCache();
Please provide the content you would like translated to English.
This will remove the registration of the memory cache service. However, it is important to note that if your Redis encounters issues, your application will not be able to use the fallback cache, which may affect the performance and availability of your application. Therefore, it is recommended that you still register the `AddDistributedMemoryCache()` service when using Redis as a distributed cache. 😊
## Step 4 Add Middleware
Please provide the content you would like translated to English.
//Add middleware
app.UseStaticFiles(new StaticFileOptions
Please provide the content you would like translated to English.
ServeUnknownFileTypes = true
});
app.UseRateLimiting();
Sure, please provide the content you would like translated to English.
Remember to place `UseRateLimit` after `UseStaticFiles`, otherwise the access count for static files in the page will be included, and they will be rate-limited very quickly.
### Step 5 Configure your rate limiting rules in `appsettings.json`
- `EnableEndpointRateLimiting` - This option should be set to true; otherwise, the rate limiting will be global and cannot be set individually for specific paths.
- `StackBlockedRequests` - By default, it should be set to false. If set to true, repeated requests to an interface after it has been rate-limited will still count towards the access count, which could potentially lead to indefinite rate-limiting.
Please provide the content you would like translated to English.
"IpRateLimiting": {
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": false,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"HttpStatusCode": 429,
"IpWhitelist": [],
"GeneralRules": [
Please provide the content you would like translated to English.
The access address of the interface that is subject to rate limiting can be set for multiple entries.
"Endpoint": "get:/api/GetUser",
//1 minute
"Period": "1m",
//Limit times 5 times
"Limit": 5
}
]
"QuotaExceededResponse": {
"Content": "{{ \"message\": \"Don't worry, you're accessing too quickly!\", \"details\": \"Rate limit has been triggered. Rate limit rule: You can only access {0} times every {1}. Please try again in {2} seconds.\" }}"
"ContentType": "application/json",
"StatusCode": 429
}
},
"ConnectionStrings": {
"Redis": "Redis server address and port number"
},
Sure, please provide the content you would like translated to English.
- {0} - Rule. Restriction
- {1} - Rule. Era
- {2} - After retrying
# Implementation Effect
API Rate Limiting Screenshot
# Test API Endpoint
[Demonstration Effect Interface Address](http://47.113.150.96:9051/api/GetUser)
# References
- Official website URL: https://github.com/stefanprodan/AspNetCoreRateLimit
Original address: https://www.cnblogs.com/deali/p/17227592.html