When building web applications, you might often want to control the frequency of user requests to prevent malicious attacks. In other words, you might want to limit the number of requests coming from an IP address during a short timespan to mitigate denial-of-service attacks. This process is known as rate limiting.
There are many Nuget packages that uses Middleware for handling user requests but there is a problem with middlewares because they affect all incoming requests! So, what is the solution if you want to control just some critical endpoints? yes, that is ActionFilters!
Let’s go to find how to use action filters as a rate limit.
Create Asp.net core API project: I’m using Visual Studio 2022 and .Net 6 1- Click on “Create new project” 2- Select Asp.net core web api
3- Enter the project name
4- Select target framework (I selected .net6.0 but you select any LTS version that installed in your system)
Ok you created the project, now you should install this Nuget package:
Install-Package DotNetRateLimiter -Version 1.0.1
And add this line to your Program.cs (.net6) or ConfigureService in startup (pre .net6)