Created
August 2, 2022 12:19
-
-
Save Kahbazi/94beef16aa145503d8407b56a46efd6c to your computer and use it in GitHub Desktop.
ASP.Net Core RateLimiting Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.RateLimiting; | |
using System.Net; | |
using System.Threading.RateLimiting; | |
var builder = WebApplication.CreateBuilder(args); | |
var app = builder.Build(); | |
var options = new RateLimiterOptions() | |
.AddPolicy<string>("user", context => | |
{ | |
if (context.User?.Identity?.IsAuthenticated ?? false) | |
{ | |
var username = context.User.FindFirst("username").Value; | |
return RateLimitPartition.CreateSlidingWindowLimiter<string>(username, key => new SlidingWindowRateLimiterOptions( | |
permitLimit: 2, | |
queueProcessingOrder: QueueProcessingOrder.OldestFirst, | |
queueLimit: 0, | |
window: TimeSpan.FromSeconds(30), | |
segmentsPerWindow: 1 | |
)); | |
} | |
else | |
{ | |
return RateLimitPartition.CreateNoLimiter<string>(string.Empty); | |
} | |
}); | |
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, IPAddress>(context => | |
{ | |
if (!IPAddress.IsLoopback(context.Connection.RemoteIpAddress)) | |
{ | |
return RateLimitPartition.CreateSlidingWindowLimiter<IPAddress>(context.Connection.RemoteIpAddress, key => new SlidingWindowRateLimiterOptions( | |
permitLimit: 10, | |
queueProcessingOrder: QueueProcessingOrder.OldestFirst, | |
queueLimit: 0, | |
window: TimeSpan.FromSeconds(30), | |
segmentsPerWindow: 1 | |
)); | |
} | |
else | |
{ | |
return RateLimitPartition.CreateNoLimiter<IPAddress>(IPAddress.Loopback); | |
} | |
}); | |
app.UseRateLimiter(options); | |
app.MapGet("/", () => "Hello World!"); | |
app.MapGet("/api/a", () => "Hello A!").RequireRateLimiting("user"); | |
app.MapGet("/api/b", () => "Hello B!").RequireRateLimiting("user"); | |
app.Run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment