Back to Aspnetcore

Rate limiting middleware samples

aspnetcore/performance/rate-limit-samples.md

latest4.4 KB
Original Source

Rate limiter samples

The following samples aren't production quality, they're examples on how to use the limiters.

Limiter with OnRejected, RetryAfter, and GlobalLimiter

The following sample:

:::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.

[!INCLUDE]

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.

Limiter with authorization

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":::

Limiter with ConcurrencyLimiter, TokenBucketRateLimiter, and authorization

The following sample:

:::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.