# Add Rate Limiting to a .NET Minimal API

Yes. An agent adds ASP.NET Core's built-in rate limiter, strict on the identity endpoints and per user elsewhere, proves it with a functional test and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-rate-limiting/dotnet/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent clones the repository into its own cloud sandbox and reads how requests reach the handlers. In a solution like jasontaylordev/CleanArchitecture, `global.json` pins the .NET 10 SDK, `Directory.Build.props` targets `net10.0` with warnings as errors, and `Directory.Packages.props` manages every package version centrally. `src/Web/Program.cs` calls `AddServiceDefaults`, `AddApplicationServices`, `AddInfrastructureServices` and `AddWebServices`, then builds a pipeline of HSTS, HTTPS redirection, an allow-everything CORS policy, static files, OpenAPI and Scalar, the exception handler, the health endpoints and finally `MapEndpoints(typeof(Program).Assembly)`. That method in `src/Web/Infrastructure/WebApplicationExtensions.cs` discovers every `IEndpointGroup` and maps it as a route group under `/api/{ClassName}`: `TodoItems`, `TodoLists` and `WeatherForecasts` each call `RequireAuthorization()`, and `Users` maps `MapIdentityApi<ApplicationUser>()`, so registration and login are anonymous endpoints under `/api/Users`. Nothing in the solution mentions a rate limiter.

It uses the limiter that ships in the framework, so `Directory.Packages.props` does not change. In `src/Web/DependencyInjection.cs`, `AddWebServices` gains `AddRateLimiter` with two named policies: `identity`, a fixed window keyed on the client address for the anonymous `Users` group, and `api`, a sliding window keyed on the user name when there is one and the client address otherwise, with the window sizes and permit counts read from a new `RateLimiting` section in `appsettings.json` through an options class so each environment can tune them. The limiter answers a rejected request with status 429 and an `OnRejected` handler that writes a `Retry-After` header from the lease's metadata and a problem-details body in the same shape `ProblemDetailsExceptionHandler` already produces. In `Program.cs`, `app.UseRateLimiter()` goes after `UseCors` and before the endpoints are mapped.

The policies are attached where the groups are built, not in each endpoint file. `MapEndpoints` applies `RequireRateLimiting("api")` to every discovered group, and `Users.Map` overrides its group with `RequireRateLimiting("identity")`, so a new `IEndpointGroup` added next month is limited without its author remembering to. The health endpoints from `MapDefaultEndpoints` are mapped outside the groups and keep running unlimited for the orchestrator. The project is also a `dotnet new` template with `#if (UseApiOnly)` regions, so the agent keeps the new code valid in both the cookie and bearer variants and does not touch the generated client under `src/Web/ClientApp`.

Before opening anything it proves the behaviour. `tests/Application.FunctionalTests` builds the web app through `WebApiFactory`, a `WebApplicationFactory<Program>`, on an Aspire test host that needs no Docker in the SQLite variant, so the agent adds a `RateLimitingTests` class that creates an `HttpClient` from the factory, posts to `/api/Users/login` one more time than the identity window allows, and asserts the last response is 429 with a `Retry-After` header, then does the same for an authorised `GET /api/TodoLists` against the `api` policy. It runs `dotnet build` and `dotnet test tests/Application.FunctionalTests tests/Application.UnitTests` with warnings as errors in its sandbox and pastes the output into the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add rate limiting to this ASP.NET Core minimal API. Read global.json, Directory.Build.props, Directory.Packages.props, src/Web/Program.cs, src/Web/DependencyInjection.cs, src/Web/Infrastructure/WebApplicationExtensions.cs, src/Web/Infrastructure/IEndpointGroup.cs, every file under src/Web/Endpoints, src/ServiceDefaults/Extensions.cs, src/Web/appsettings.json and the functional test infrastructure under tests/Application.FunctionalTests first, and confirm no limiter is configured today. Use the framework's built-in rate limiter without adding a package. Define a fixed-window policy keyed on the client address for the anonymous identity endpoints and a sliding-window policy keyed on the user name, falling back to the address, for every other endpoint group, with limits read from an appsettings section through an options class. Reject with 429, a Retry-After header and a problem-details body. Apply the general policy where endpoint groups are discovered so new groups inherit it, override the Users group with the identity policy, and leave the health endpoints unlimited. Keep the template's conditional regions valid. Add functional tests that drive both policies over HTTP through the existing WebApplicationFactory. In your sandbox run dotnet build and dotnet test for the functional and unit test projects and open a pull request that lists the files changed, the two policies and their defaults, and the command output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request touching `src/Web/Program.cs`, `src/Web/DependencyInjection.cs`, `src/Web/Infrastructure/WebApplicationExtensions.cs`, `src/Web/Endpoints/Users.cs`, `src/Web/appsettings.json`, a new options class, and a new test file under `tests/Application.FunctionalTests`. The description lists the two policies with their default window and permit values, says which routes each covers, and shows the 429 body a client will see.

The run's record holds the `dotnet build` and `dotnet test` output from the sandbox, including the new tests driving both policies over HTTP, so a reviewer can see the limiter rejects at the configured count and not before.

Before merging, a reviewer sets the production values in the environment's configuration, since the defaults are chosen to make the tests fast rather than to fit real traffic, and decides whether the API runs behind a proxy, in which case the client address the policies key on must come from forwarded headers the pipeline does not yet read.

## Run it on every Linear issue labelled api

A team that tracks API work in Linear starts one run per issue from an automation with a `linear` trigger on the `api` label, in the Project that holds the solution. The trigger adds the issue after this prompt and fills in no placeholder, so an issue that asks for a concurrency limit on an expensive report endpoint, a token-bucket policy for a partner integration, or a different key than the user name is what the agent reads and builds.

Each run clones the solution into its own sandbox, restores and builds it there, and opens its own pull request linking the issue. An automation run has its own `max_runs_per_hour` cap, and a second labelled issue gets a second sandbox.

## Why run it on Rush?

Rate limiting is easy to add in the wrong place: on one endpoint instead of the discovery code that maps all of them, keyed on an address behind a proxy, or with a 429 that carries no `Retry-After`. The agent reads the endpoint discovery, the identity mapping and the exception handler together and tests both policies over real HTTP against the solution's own test host, so the pull request arrives with the rejection path shown rather than described.

The sandbox restores the pinned SDK and runs the Aspire-backed functional tests from a clean checkout, the same way the repository's `build.yml` does. The same request runs against every .NET service an organisation maintains, each in its own sandbox with its own endpoint files read first, and each pull request keeps the full command record for the reviewer.

## Frequently asked questions

### Does it add a package?

No. The rate limiting middleware is part of ASP.NET Core, so `Directory.Packages.props` is untouched and the central version pinning the solution relies on is unaffected.

### Why two policies?

Login and registration are anonymous and are what an attacker hammers, so they get a small fixed window keyed on the client address. Authenticated endpoints get a larger sliding window keyed on the user, so one busy client cannot consume another's allowance.

### What does a rejected client receive?

A 429 status, a `Retry-After` header computed from the limiter's lease, and a problem-details body in the same shape the exception handler already returns, so existing clients parse it without a new case.

### What about requests behind a load balancer?

The address-keyed policy sees the proxy's address unless forwarded headers are read, which the pipeline does not do today. The pull request names that as the one deployment decision to settle, since trusting those headers depends on the proxy in front of the API.

### Will the health endpoints be limited?

No. They are mapped by `MapDefaultEndpoints` outside the discovered groups, so the orchestrator's liveness and readiness probes never count against a policy.

## More .NET jobs

- [Add Structured Logging to a .NET App](https://getrush.ai/run/add-structured-logging/dotnet/)
- [Fix a Failing CI Build in a .NET Project](https://getrush.ai/run/fix-failing-ci/dotnet/)
- [Fix "warning NETSDK1138: The target framework 'net6.0' is out of support" and Get a .NET 6 API Running on .NET 10](https://getrush.ai/run/fix-netsdk1138-target-framework-out-of-support/dotnet/)

## The same job on other stacks

- [Add Rate Limiting to an Echo API](https://getrush.ai/run/add-rate-limiting/echo/)
- [Add Rate Limiting to an Express API from a Linear Issue](https://getrush.ai/run/add-rate-limiting/express/)
- [Add Rate Limiting to a FastAPI API](https://getrush.ai/run/add-rate-limiting/fastapi/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
