Ultimate ASP.NET Core Web API 26 RATE LIMITING AND THROTTLING

26 RATE LIMITING AND THROTTLING
26 速率限制和限制

Rate Limiting allows us to protect our API against too many requests that can deteriorate our API’s performance. API is going to reject requests that exceed the limit. Throttling queues exceeded requests for possible later processing. The API will eventually reject the request if processing cannot occur after a certain number of attempts.‌
Rate Limiting 使我们能够保护我们的 API 免受过多的请求的影响,这些请求可能会降低 API 的性能。API 将拒绝超过限制的请求。限制队列超出了以后可能处理的请求。如果在一定次数的尝试后无法进行处理,则 API 最终将拒绝该请求。

For example, we can configure our API to create a limitation of 100 requests/hour per client. Or additionally, we can limit a client to the maximum of 1,000 requests/day per IP and 100 requests/hour. We can even limit the number of requests for a specific resource in our API; for example, 50 requests to api/companies.
例如,我们可以将 API 配置为为每个客户端创建 100 个请求/小时的限制。或者,我们可以将客户端限制为每个 IP 每天最多 1000 个请求,每小时最多 100 个请求。我们甚至可以在 API 中限制对特定资源的请求数量;例如,对 API/Companies 的 50 个请求。

To provide information about rate limiting, we use the response headers. They are separated between Allowed requests, which all start with the X- Rate-Limit and Disallowed requests.
为了提供有关速率限制的信息,我们使用响应标头。它们分为 Allowed 请求,这些请求都以 X-Rate-Limit 和 Disallowed 请求开头。

The Allowed requests header contains the following information :
Allowed requests 标头包含以下信息:

• X-Rate-Limit-Limit – rate limit period.
X-Rate-Limit-Limit – 速率限制期。

• X-Rate-Limit-Remaining – number of remaining requests.
X-Rate-Limit-Remaining – 剩余请求数。

• X-Rate-Limit-Reset – date/time information about resetting the request limit.
X-Rate-Limit-Reset – 有关重置请求限制的日期/时间信息。

For the disallowed requests, we use a 429 status code; that stands for too many requests. This header may include the Retry-After response header and should explain details in the response body.
对于不允许的请求,我们使用 429 状态代码;这代表请求太多。此标头可能包括 Retry-After 响应标头,并应在响应正文中说明详细信息。

26.1 Implementing Rate Limiting

26.1 实现速率限制

To start, we have to install the AspNetCoreRateLimit library in the main project:‌
首先,我们必须在主项目中安装 AspNetCoreRateLimit 库:

alt text

Then, we have to add it to the service collection. This library uses a memory cache to store its counters and rules. Therefore, we have to add the MemoryCache to the service collection as well.
然后,我们必须将其添加到服务集合中。此库使用内存缓存来存储其计数器和规则。因此,我们还必须将 MemoryCache 添加到服务集合中。

That said, let’s add the MemoryCache:
也就是说,让我们添加 MemoryCache:

builder.Services.AddMemoryCache();

After that, we are going to create another extension method in the ServiceExtensions class:
之后,我们将在 ServiceExtensions 类中创建另一个扩展方法:

public static void ConfigureRateLimitingOptions(this IServiceCollection services) { var rateLimitRules = new List<RateLimitRule> { new RateLimitRule { Endpoint = "*", Limit = 3, Period = "5m" } }; services.Configure<IpRateLimitOptions>(opt => { opt.GeneralRules = rateLimitRules; }); services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>(); services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>(); }

We create a rate limit rules first, for now just one, stating that three requests are allowed in a five-minute period for any endpoint in our API. Then, we configure IpRateLimitOptions to add the created rule. Finally, we have to register rate limit stores, configuration, and processing strategy as a singleton. They serve the purpose of storing rate limit counters and policies as well as adding configuration.
我们首先创建一个速率限制规则,现在只有一个,规定在 5 分钟内允许对 API 中的任何终端节点发出三个请求。然后,我们配置 IpRateLimitOptions 以添加创建的规则。最后,我们必须将 Rate limit 存储、配置和处理策略注册为单例。它们用于存储速率限制计数器和策略以及添加配置。

Now, we have to modify the Program class again:
现在,我们必须再次修改 Program 类:

builder.Services.ConfigureRateLimitingOptions(); 
builder.Services.AddHttpContextAccessor();
builder.Services.AddMemoryCache();

Finally, we have to add it to the request pipeline:
最后,我们必须将其添加到请求管道中:

app.UseIpRateLimiting();
app.UseCors("CorsPolicy");

And that is it. We can test this now:
就是这样。我们现在可以测试一下:
https://localhost:5001/api/companies

alt text

So, we can see that we have two requests remaining and the time to reset the rule. If we send an additional three requests in the five-minute period of time, we are going to get a different response:
因此,我们可以看到我们还剩下两个请求和重置规则的时间。如果我们在 5 分钟内额外发送 3 个请求,我们将得到不同的响应:
https://localhost:5001/api/companies

alt text

The status code is 429 Too Many Requests and we have the Retry-After header.
状态代码为 429 Too Many Requests,我们有 Retry-After 标头。

We can inspect the GET主体 as well:
我们也可以检查身体:

https://localhost:5001/api/companies

alt text

So, our rate limiting works.
因此,我们的速率限制有效。

There are a lot of options that can be configured with Rate Limiting and you can read more about them on the AspNetCoreRateLimit GitHub page.
有很多选项可以使用 Rate Limiting 进行配置,您可以在 AspNetCoreRateLimit GitHub 页面上阅读有关它们的更多信息。

Leave a Reply

Your email address will not be published. Required fields are marked *