Rate Limiting in ASP.NET Core Web API
This guide shows you how to add rate limiting to an ASP.NET Core Web API so you can control how many requests a client can make in a given time window. You’ll learn to configure built-in policies, apply them to controllers or endpoints, and test the behavior. No external packages are needed because the middleware is included in .NET 7 and later.
What You’ll Need
- An ASP.NET Core Web API project (targeting .NET 7 or later)
- Visual Studio 2022, VS Code, or any code editor
- Basic familiarity with
Program.csand middleware - Optional: Postman, curl, or a browser to test the API
Step-by-Step
- Create a new Web API project if you don’t have one. In Visual Studio, select File > New > Project, choose ASP.NET Core Web API, and click Create. Or use the CLI:
dotnet new webapi -n RateLimitedApi. - Add the rate limiting services in
Program.cs. After thebuilderis created, addbuilder.Services.AddRateLimiter();. This registers the necessary services with the dependency injection container. - Define a rate limit policy. Inside the
AddRateLimitercall, configure a fixed window policy. For example, allow 10 requests per minute per client IP:builder.Services.AddRateLimiter(options => { options.AddFixedWindowLimiter("fixed", limiterOptions => { limiterOptions.PermitLimit = 10; limiterOptions.Window = TimeSpan.FromMinutes(1); limiterOptions.QueueLimit = 2; }); });The
PermitLimitis the maximum number of requests allowed in the window,Windowis the time span, andQueueLimitis how many requests can wait if the limit is reached (they will be processed as soon as a slot frees up). - Add the rate limiting middleware to the request pipeline. After
var app = builder.Build();, addapp.UseRateLimiter();. Place it before any endpoint mapping, typically afterapp.UseHttpsRedirection()and beforeapp.MapControllers(). - Apply the policy to controllers or endpoints. You have two main options:
- Globally: Apply the policy to all endpoints by setting
options.GlobalLimiterin theAddRateLimiterconfiguration. For example:options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context => RateLimitPartition.GetFixedWindowLimiter(context.Connection.RemoteIpAddress?.ToString(), _ => new FixedWindowRateLimiterOptions { PermitLimit = 10, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 })); - Per endpoint: Use the
[EnableRateLimiting("fixed")]attribute on a controller or action method. For example:[ApiController] [Route("api/[controller]")] [EnableRateLimiting("fixed")] public class WeatherController : ControllerBase { [HttpGet] public IActionResult Get() => Ok(); }To disable rate limiting on a specific endpoint, use
[DisableRateLimiting].
- Globally: Apply the policy to all endpoints by setting
- Customize the response when the limit is exceeded. By default, the middleware returns a
503 Service Unavailablestatus. You can change this by settingoptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests;and optionally add a custom response usingoptions.OnRejected. For example:options.OnRejected = async (context, cancellationToken) => { context.HttpContext.Response.ContentType = "application/json"; await context.HttpContext.Response.WriteAsync("{\"error\":\"Too many requests. Please slow down.\"}", cancellationToken); }; - Build and run the project. Press F5 or run
dotnet run. The API will now enforce the rate limit. - Test the rate limiting. Use a tool like Postman or curl to send multiple requests quickly. For example, with the policy above, send 11 requests in under a minute. The 11th request should receive a 429 (if you set the rejection status) or 503 (default). The first 10 requests should succeed.
Common Mistakes
- Forgetting to call
UseRateLimiter(): Adding the service but not the middleware means the limits are never enforced. - Placing middleware incorrectly: If
UseRateLimiter()is placed afterMapControllers(), it won’t run for API requests. It must be before endpoint mapping. - Using the wrong partition key: If you use a global limiter with a partition key that is null (e.g., when the client IP is not available), all requests share the same bucket, which can cause unexpected blocking. Always provide a fallback key like
"unknown". - Not setting
QueueLimitappropriately: If you set a queue limit, requests will wait instead of being rejected. This can cause delays. For simple rate limiting, set it to 0 to reject immediately. - Applying the attribute to a base class: If you put
[EnableRateLimiting]on a base controller, all derived controllers inherit it. This might be unintentional. Be explicit.
Tips
- Use the built-in partitioners for common scenarios:
PartitionedRateLimiter.Create<HttpContext, string>withRateLimitPartition.GetFixedWindowLimiteris straightforward. You can also useGetSlidingWindowLimiterorGetTokenBucketLimiterfor more advanced algorithms. - Expose rate limit headers: Add middleware to include
X-RateLimit-Limit,X-RateLimit-Remaining, andX-RateLimit-Resetheaders so clients can see their status. This is helpful for API consumers. - Test with different client IPs: When testing locally, all requests come from
127.0.0.1. To simulate different clients, use theX-Forwarded-Forheader (if your app trusts it) or run tests from multiple machines. - Use configuration for limits: Store limits in
appsettings.jsonso you can change them without recompiling. For example, bind the limiter options to a config section. - Consider using the
RateLimitPartitionwith a user ID if you have authentication. This allows per-user limits instead of per-IP, which is more fair for shared IPs.
Troubleshooting
- Rate limiting not working: Check that
UseRateLimiter()is present and placed beforeMapControllers(). Also verify the policy name matches the attribute name exactly (case-sensitive). - Getting 503 instead of 429: The default rejection status is 503. If you want 429, set
RejectionStatusCodeto 429 in theAddRateLimiteroptions. - All requests are blocked immediately: This often happens when the partition key is null, causing all requests to share a single bucket that fills up fast. Ensure your partition key is unique per client (e.g., IP or user ID).
- Requests are delayed instead of rejected: This is due to a non-zero
QueueLimit. If you don’t want queuing, set it to 0. - Attribute not found: The
[EnableRateLimiting]attribute is in theMicrosoft.AspNetCore.RateLimitingnamespace. Addusing Microsoft.AspNetCore.RateLimiting;to your controller file.
Frequently Asked Questions
Can I use rate limiting in .NET 6 or earlier?
No, the built-in rate limiting middleware was introduced in .NET 7. For .NET 6 or earlier, you would need a third-party library like AspNetCoreRateLimit.
How do I set different limits for different endpoints?
Define multiple policies in AddRateLimiter (e.g., “fixed” and “strict”) and apply them with [EnableRateLimiting("policyName")] on each controller or action.
Does rate limiting work with authentication?
Yes, you can partition by user ID instead of IP. For example, in the global limiter, use context.User.Identity?.Name as the partition key.
What happens if the client sends more requests than the limit?
By default, the middleware returns a 503 status. If you set RejectionStatusCode to 429, it returns 429 Too Many Requests. You can also customize the response body via OnRejected.
Can I disable rate limiting for a specific endpoint?
Yes, use the [DisableRateLimiting] attribute on that controller or action. This overrides any global or controller-level policy.
How do I see the remaining limit for a client?
You can add custom middleware to read the RateLimitLease from the context and add headers. The lease is available via context.Features.Get<IRateLimiterFeature>()?.Lease.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.