AspNetCore.Docs.Samples/fundamentals/middleware/rate-limit/WebRateLimitAuth/SampleRateLimiterPolicy.cs

44 lines
1.6 KiB
C#
Raw Normal View History

2022-08-24 11:00:59 +08:00
// <snippet_1>
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using WebRateLimitAuth.Models;
namespace WebRateLimitAuth;
2022-08-24 11:00:59 +08:00
// <snippet>
public class SampleRateLimiterPolicy : IRateLimiterPolicy<string>
{
private Func<OnRejectedContext, CancellationToken, ValueTask>? _onRejected;
private readonly MyRateLimitOptions _options;
public SampleRateLimiterPolicy(ILogger<SampleRateLimiterPolicy> logger,
IOptions<MyRateLimitOptions> options)
{
_onRejected = (ctx, token) =>
{
ctx.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
logger.LogWarning($"Request rejected by {nameof(SampleRateLimiterPolicy)}");
return ValueTask.CompletedTask;
};
_options = options.Value;
}
public Func<OnRejectedContext, CancellationToken, ValueTask>?
OnRejected { get => _onRejected; }
2022-08-24 11:00:59 +08:00
// </snippet>
public RateLimitPartition<string> GetPartition(HttpContext httpContext)
{
return RateLimitPartition.CreateSlidingWindowLimiter<string>(string.Empty,
key => new SlidingWindowRateLimiterOptions(
permitLimit: _options.permitLimit,
queueProcessingOrder: QueueProcessingOrder.OldestFirst,
queueLimit: _options.queueLimit,
window: TimeSpan.FromSeconds(_options.window),
segmentsPerWindow: _options.segmentsPerWindow));
}
}
2022-08-24 11:00:59 +08:00
// </snippet_1>