Stefan
Stefan

Reputation: 21

Rate limiting middleware in ASP.NET Core MVC

I am trying to add the rate limiting middleware to my ASP.NET Core MVC web application.

I add a global and partitioned FixedWindowLimiter via

services.AddRateLimiter(...) 

and activate it using

app.UseRateLimiter()

I have a controller, which must not be rate limited and therefore I added the attribute [DisableRateLimiting] on that one. But, this attribute is ignored by the middleware and I have no idea, why this is happening.

In the documentation is written, that app.UseRouting() must be called before app.UseRateLimiter(). I do not use app.UseRouting(), but app.UseMvc(...), which is the last one in the pipeline.

When I put app.UseRateLimiter() after app.UseMvc(...), the global rate limiter is not working. Otherwise, the attribute on the controller is not working.

Upvotes: 2

Views: 357

Answers (1)

Mohamed Shaaban
Mohamed Shaaban

Reputation: 31

Switch from app.UseMvc() to app.UseRouting() and app.UseEndpoints(). This aligns with the middleware pipeline required for the rate limiter and ensures the pipeline order is correct:

app.UseRouting();
app.UseRateLimiter();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

This should fix both the global rate limiter and the [DisableRateLimiting] attribute.

Upvotes: 1

Related Questions