In ASP.NET Core 10, which three calls put a named fixed-window rate limit on one Minimal API endpoint, and what breaks without each?
answer
- services, middleware, endpoint metadata
- AddRateLimiter registers named policies
- UseRateLimiter adds the middleware
- RequireRateLimiting or [EnableRateLimiting]
- unattached policy limits nothing
basics
~10 sRegister a named policy with AddRateLimiter and AddFixedWindowLimiter, add the middleware with app.UseRateLimiter(), and attach the policy with RequireRateLimiting or [EnableRateLimiting]. UseRateLimiter without AddRateLimiter throws at startup; an unattached policy limits nothing.
solid answer
~40 sThe rate limiter ships in the shared framework (`Microsoft.AspNetCore.RateLimiting`), so there is no package to add. `builder.Services.AddRateLimiter(o => o.AddFixedWindowLimiter("free", w => { w.PermitLimit = 60; w.Window = TimeSpan.FromMinutes(1); }))` registers the services and a named policy, `app.UseRateLimiter()` adds the middleware, and `.RequireRateLimiting("free")` on the endpoint (or `[EnableRateLimiting("free")]` on a controller or action) attaches it. Leave out `AddRateLimiter` and `UseRateLimiter` throws an `InvalidOperationException` when the pipeline is built; leave out the middleware and no policy is ever evaluated; leave out the attach step and the endpoint is unlimited, because the middleware only limits endpoints that carry a policy unless a `GlobalLimiter` is set. A rejected request gets 503 unless you change `RejectionStatusCode`.
code
csharp · 22 linesusing Microsoft.AspNetCore.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("free", window =>
{
window.PermitLimit = 60;
window.Window = TimeSpan.FromMinutes(1);
window.QueueLimit = 0;
});
});
var app = builder.Build();
app.UseRateLimiter();
app.MapGet("/forecast/{city}", (string city) => Results.Ok(new { city, tempC = 18 }))
.RequireRateLimiting("free");
app.Run();go deeper
Recall the three pieces: AddRateLimiter with a named policy, UseRateLimiter, and RequireRateLimiting or [EnableRateLimiting] on the endpoint. Know that rejections default to 503.
Explain what the middleware checks per request: DisableRateLimiting metadata first, then whether an EnableRateLimiting policy or a GlobalLimiter exists, and only then acquiring a lease.
Point out the failures that only surface at run time: unknown policy names on first request, zero PermitLimit, and the 503 default; cover them with an integration test per limited endpoint.
Decide where limits belong: in-app policies per endpoint group versus a global ceiling versus a proxy in front, and who owns the numbers when product tiers change.
## Where the rate limiter lives ASP.NET Core 10 has a built-in **rate limiting middleware** in the `Microsoft.AspNetCore.RateLimiting` namespace. It has been part of the shared framework (`Microsoft.AspNetCore.App`) since ASP.NET Core 7, so a `net10.0` web project uses it without a `PackageReference`. The limiter algorithms themselves come from the BCL namespace `System.Threading.RateLimiting` (`FixedWindowRateLimiter`, `TokenBucketRateLimiter` and friends); the ASP.NET Core package wraps them in a middleware that decides, per request, which limiter applies. Limiting one endpoint with a named policy takes **three pieces**, and each one fails differently when it is missing. ## The three pieces | Piece | Call | What it does | Without it | |---|---|---|---| | Services and policies | `builder.Services.AddRateLimiter(options => ...)` | registers the middleware's services and stores named policies in `RateLimiterOptions` | `app.UseRateLimiter()` throws `InvalidOperationException` ("Unable to find the required services ... AddRateLimiter") when the pipeline is built | | Middleware | `app.UseRateLimiter()` | adds the middleware that acquires a permit for each request | policies are registered but never consulted; every request passes | | Attachment | `.RequireRateLimiting("free")` or `[EnableRateLimiting("free")]` | adds endpoint metadata naming the policy | the endpoint is not limited, unless `RateLimiterOptions.GlobalLimiter` is set | The third row surprises people most. Registering `AddFixedWindowLimiter("free", ...)` only **names** a policy. The middleware looks at the selected endpoint's metadata; when it finds neither an `EnableRateLimitingAttribute` nor a global limiter, it simply calls the next middleware. ## Attaching a policy - **Minimal APIs**: chain `.RequireRateLimiting("free")` on the `RouteHandlerBuilder` returned by `MapGet`, or on a `RouteGroupBuilder` from `app.MapGroup("/v1")` so every endpoint in the group inherits it. - **Controllers**: put `[EnableRateLimiting("free")]` on the controller class or on an action. `RequireRateLimiting("free")` on `app.MapControllers()` attaches it to every action at once. - **Razor Pages**: the attribute goes on the page model class, not on `OnGet` or `OnPost` handlers. - **Opting out**: `[DisableRateLimiting]` or `.DisableRateLimiting()` removes every limit from that endpoint. `RequireRateLimiting` literally adds an `EnableRateLimitingAttribute` instance to the endpoint's metadata, so the attribute and the fluent call are two spellings of the same thing. ## What the middleware does on each request 1. If the endpoint carries `DisableRateLimitingAttribute`, call the next middleware and stop. 2. If the endpoint has no `EnableRateLimitingAttribute` and no `GlobalLimiter` is configured, call the next middleware and stop. 3. Otherwise acquire a lease from the global limiter (if any), then from the endpoint's policy. 4. If both grant a permit, run the rest of the pipeline and release the lease when the request completes. 5. If either refuses, set `Response.StatusCode` to `RateLimiterOptions.RejectionStatusCode` (**503 Service Unavailable** by default) and call `OnRejected` if one is configured. ## Mistakes that show up only at run time - **A misspelled policy name** compiles fine; the first request to that endpoint throws `InvalidOperationException` ("This endpoint requires a rate limiting policy with name ..., but no such policy exists"). - **Registering the same name twice** throws `ArgumentException` ("There already exists a policy with the name ...") when the options are built. - **Forgetting `PermitLimit` or `Window`** leaves them at 0 and `TimeSpan.Zero`; the limiter constructor throws `ArgumentException` the first time a request needs that limiter. - **Expecting 429**: clients see 503 until you set `RejectionStatusCode` or write the status in `OnRejected`. For the free tier of a public weather-data API, the minimal working shape is a fixed window of 60 requests a minute on the `/forecast` endpoint, as in the code example. Note that this particular shape is one shared counter for every caller; giving each user or IP its own allowance takes a partitioned policy.
- How do you apply one rate limiting policy to every endpoint under /v1 in a Minimal API?Call `RequireRateLimiting("free")` on the `RouteGroupBuilder` returned by `app.MapGroup("/v1")`; group conventions flow to every endpoint mapped inside it. An endpoint in that group opts out with `.DisableRateLimiting()`. If the limit must cover every request in the app, routed or not, configure `RateLimiterOptions.GlobalLimiter` instead of a named policy.
- What happens if an endpoint asks for a policy name that was never registered?Nothing at startup. The endpoint limiter resolves the name lazily, so the first request to that endpoint throws `InvalidOperationException` with "This endpoint requires a rate limiting policy with name ..., but no such policy exists." An integration test that calls each limited endpoint once catches the typo before production does.
- Adding AddFixedWindowLimiter alone limits every endpoint in the app.
- Rate limiting in ASP.NET Core 10 needs a third-party NuGet package.
- A misspelled policy name fails at compile time or at startup.
- Rejected requests get 429 Too Many Requests out of the box.
- AddRequestTimeouts and WithRequestTimeout are how you cap requests per minute.
Assumes ASP.NET Core 10; the Microsoft.AspNetCore.RateLimiting middleware has been in the shared framework since ASP.NET Core 7, so no package reference is needed.