AspNetCoreRateLimit icon indicating copy to clipboard operation
AspNetCoreRateLimit copied to clipboard

Reading the counter value from the cache

Open LidiaSongstad opened this issue 3 years ago • 4 comments

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,

LidiaSongstad avatar Sep 16 '22 12:09 LidiaSongstad

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.

ThomasArdal avatar Feb 21 '23 13:02 ThomasArdal

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,

LidiaSongstad avatar Feb 21 '23 13:02 LidiaSongstad

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;
}

ThomasArdal avatar Feb 21 '23 14:02 ThomasArdal

You are welcome. Thanks for your suggestion..

LidiaSongstad avatar Feb 22 '23 04:02 LidiaSongstad