aspnetcore/performance/rate-limit-samples.md
The following samples aren't production quality, they're examples on how to use the limiters.
OnRejected, RetryAfter, and GlobalLimiterThe following sample:
Creates a xref:Microsoft.AspNetCore.RateLimiting.RateLimiterOptions.OnRejected%2A?displayProperty=nameWithType callback that's called when a request exceeds the specified limit. retryAfter can be used with the xref:System.Threading.RateLimiting.TokenBucketRateLimiter, Fixed Window Limiter, and Sliding Window Limiter because these algorithms are able to estimate when more permits are added. The xref:System.Threading.RateLimiting.ConcurrencyLimiter has no way of calculating when permits are available.
Adds the following limiters:
SampleRateLimiterPolicy that implements the xref:Microsoft.AspNetCore.RateLimiting.IRateLimiterPolicy%601 interface. The SampleRateLimiterPolicy class is shown later in this article.SlidingWindowLimiter:
GlobalLimiter creates a partition for each xref:System.Net.IPAddress.:::code language="csharp" source="~/../AspNetCore.Docs.Samples/fundamentals/middleware/rate-limit/WebRateLimitAuth/Program.cs" id="snippet_1":::
[!WARNING] Creating partitions on client IP addresses makes the app vulnerable to Denial of Service Attacks which employ IP Source Address Spoofing. For more information, see BCP 38 RFC 2827 Network Ingress Filtering: Defeating Denial of Service Attacks which employ IP Source Address Spoofing.
For the complete Program.cs file, see the samples repository.
The SampleRateLimiterPolicy class
:::code language="csharp" source="~/../AspNetCore.Docs.Samples/fundamentals/middleware/rate-limit/WebRateLimitAuth/SampleRateLimiterPolicy.cs" id="snippet_1":::
In the preceding code, xref:Microsoft.AspNetCore.RateLimiting.RateLimiterOptions.OnRejected uses xref:Microsoft.AspNetCore.RateLimiting.OnRejectedContext to set the response status to 429 Too Many Requests. The default rejected status is 503 Service Unavailable.
The following sample uses JSON Web Tokens (JWT) and creates a partition with the JWT access token. In a production app, the JWT would typically be provided by a server acting as a Security token service (STS). For local development, the dotnet user-jwts command line tool can be used to create and manage app-specific local JWTs.
:::code language="csharp" source="~/../AspNetCore.Docs.Samples/fundamentals/middleware/rate-limit/WebRateLimitAuth/Program.cs" id="snippet_jwt":::
ConcurrencyLimiter, TokenBucketRateLimiter, and authorizationThe following sample:
ConcurrencyLimiter with a policy name of "get" that is used on the Razor Pages.TokenBucketRateLimiter with a partition for each authorized user and a partition for all anonymous users.:::code language="csharp" source="~/../AspNetCore.Docs.Samples/fundamentals/middleware/rate-limit/WebRateLimitAuth/Program.cs" id="snippet_adm2":::
See the samples repository for the complete Program.cs file.