I have previously written about Throttling in the pre-core times, and this is sort of the update to that post – with a bit of fixes and tweaks.
Lets get to it;
A few changes:
In my last post I did things a bit differently, for instance; I used to throw a custom exception type and handle that as a response, I have learned that this is an anti-pattern and is strongly discouraged (at least by David Fowler).
Anyway now we return a class, which is basically just my old ApiException type, just without the inherited bits of Exception. – this is both cheaper and cleaner.
Also since we are using .NET Core, we are using IMemoryCache instead of HttpRuntime.Cache – which is also nice.
services.AddMemoryCache();
On to the attribute:
There isn’t a lot to it to be honest.
- Check for existence of cache entry
- If none, create one and set allowExecute = true
- If allowExecute != true, return throttle response and short-circuit the pipeline.
Do note that this throttle uses IP as it’s target, but could easily be username or similar.
Usage:
[IPThrottling("GetItems", 300)]
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
The above throttles for 300 seconds for the GetItems key, so you can group together functionality as well, if you really need to.
Ill talk about the custom response in a different blogpost