"In computer networks, rate limiting is used to control the rate of traffic sent or received by a network interface controller and is used to prevent DDoS attacks."
...We're not going to be looking at preventing DDoS attacks today, but we are going to look at a simple method for limiting the number of times your users can request a particular endpoint within your C# ASP.Net Core Web Api.
Enter "ASP.Net Core Action Filter Attributes"...
The C# ASP.Net MVC Core framework supports four different types of filters:
- Authorization filters – Implements the
- Action filters – Implements the
- Result filters – Implements the
- Exception filters – Implements the
Today we're going to look at using an action filter, which is an attribute. You can apply most action filters to either an individual controller action or an entire controller.
"Action filters are used to implement the logic that get executed before or after a controller action executes."
To begin with, we need a class that inherits from ActionFilterAttribute.
Our action filter attribute contains a few properties - A name for uniqueness, an integer to store the number of seconds we're basing our rate limiting on, and a cache for managing our rate limiting.
Next, we need to override the virtual OnActionExecuting method from our inherited class. Within this method we are doing the following -
1) Obtaining the users ip address.
2) Storing the ip address in our memory cache, with a timeout based on the number of seconds we have assigned to our rate limiting action filter attribute.
3) Returning an error message and a relevant status code (HTTP 429), in the event that the user hits our rate limit for the Api.
Now to apply our action filter attribute to our desired controller action. I've added a simple Api endpoint for this example, and applied the attribute to the method, stating that we want to rate limit to 1 request, every 5 seconds.
Let's now submit multiple requests to our endpoint and see what happens -
...As expected, our action filter attribute returned an error message, along with an HTTP 429 "Too Many Requests" status code. Enjoy!
Download Github Code Sample
Feel free to DOWNLOAD the sample code of the aforementioned implementation from my Github account.
Subscribe to Simon Gilbert Developer Blog
Get the latest posts delivered right to your inbox