.Net RateLimit with ActionFilters!

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 de…


This content originally appeared on DEV Community and was authored by DEV Community

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.
I’m using Visual Studio 2022 and .Net 6

1- Click on “Create new project”
2- Select Asp.net core web api

asp.net core web api

3- Enter the project name

asp.net core project name

4- Select target framework (I selected .net6.0 but you select any LTS version that installed in your system)

asp.net core .net version

Ok you created the project, now you should install this Nuget package:

Install-Package DotNetRateLimiter -Version 1.0.0

And add this line to your Program.cs (.net6) or ConfigureService in startup (pre .net6)

builder.Services.AddRateLimitService(builder.Configuration);

Now you use it the rate limit on your Action methods:

[HttpGet]
[RateLimit(PeriodInSec = 60, Limit = 3)]
public IEnumerable<WeatherForecast> Get()
{
    return Enumerable.Range(1, 5).Select(index => new 
    WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
}

By this way the action only allows 3 requests per minute let’s test it in swagger. if you try to call api more than 3 times it gets 429 (Too Many request):

test rate limit

Nice! it works.
So, what if you want restrict the action method with parameters even in route or query string, it could be possible like:

[HttpGet("forecast/{id1}/{id2}")]
[RateLimit(PeriodInSec = 60, Limit = 3, RouteParams = "id1,id2", QueryParams = "name1,name2")]
public IEnumerable<WeatherForecast> Get(int id1, string id2, string name1, string name2)
{
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
        .ToArray();
}

It is possible to have multiple route parameters or query string parameters and you can limit request based on incoming values.
You can customize the rate limit response if needed, for sake of this you need to add config into appsettings.json file:

As you noticed there are some options that can be useful, the RateLimit uses InMemory cache by default, but if you set up a Redis connection it will use Redis, it is recommended that use Redis to check the rate limit in distributed applications. By default, it limits the IP address for control requests but you can set ClientIdentifier in the request headers and the header name is configurable.
you can see the other options in the Github repository:
https://github.com/SaeedEsmaeelinejad/DotNet.RateLimit


This content originally appeared on DEV Community and was authored by DEV Community


Print Share Comment Cite Upload Translate Updates
APA

DEV Community | Sciencx (2022-02-27T19:58:57+00:00) .Net RateLimit with ActionFilters!. Retrieved from https://www.scien.cx/2022/02/27/net-ratelimit-with-actionfilters/

MLA
" » .Net RateLimit with ActionFilters!." DEV Community | Sciencx - Sunday February 27, 2022, https://www.scien.cx/2022/02/27/net-ratelimit-with-actionfilters/
HARVARD
DEV Community | Sciencx Sunday February 27, 2022 » .Net RateLimit with ActionFilters!., viewed ,<https://www.scien.cx/2022/02/27/net-ratelimit-with-actionfilters/>
VANCOUVER
DEV Community | Sciencx - » .Net RateLimit with ActionFilters!. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/27/net-ratelimit-with-actionfilters/
CHICAGO
" » .Net RateLimit with ActionFilters!." DEV Community | Sciencx - Accessed . https://www.scien.cx/2022/02/27/net-ratelimit-with-actionfilters/
IEEE
" » .Net RateLimit with ActionFilters!." DEV Community | Sciencx [Online]. Available: https://www.scien.cx/2022/02/27/net-ratelimit-with-actionfilters/. [Accessed: ]
rf:citation
» .Net RateLimit with ActionFilters! | DEV Community | Sciencx | https://www.scien.cx/2022/02/27/net-ratelimit-with-actionfilters/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.