AspNetCoreRateLimit
AspNetCoreRateLimit copied to clipboard
Reading the counter value from the cache
Hi - There are examples to read the policy details from the policy store. Can we read the counter value from the counter store . we are using distributed cache to store the values.
Thanks,
Did you find a way to do this? I'm thinking about pulling some stats from the store to warn users when getting close to the limit, etc.
yes.. figured out a way to read from the cache by referring the code to understand how the keys are generated to store the counter value .. var bytes = Encoding.UTF8.GetBytes($"crlc_{clientId}_{period}"); using var algorithm = SHA1.Create(); var hash = algorithm.ComputeHash(bytes); var key = Convert.ToBase64String(hash); var rateLimitCounter = (await _cache.GetAsync(key)); if (rateLimitCounter.HasValue) { RateLimitCounter value = (await _cache.GetAsync(key)).Value; }
Hope this helps .. If you found a better way , please share..
Thanks,
Thank you very much. I am able to pull the counter with that code 👍 Suggestions to your code. You can inject IOptions<ClientRateLimitOptions> and get the value from that. Then crlc will be accessible through options.RateLimitCounterPrefix. Not sure if that string ever changes so may not be a huge benefit. Another is that you can maybe optimize the code a bit by changing it to:
var rateLimitCounter = await _cache.GetAsync(key);
if (rateLimitCounter.HasValue)
{
RateLimitCounter value = rateLimitCounter.Value;
}
You are welcome. Thanks for your suggestion..