# Add CSV Export to an ASP.NET Core API

Yes. An agent adds an export query, a CSV builder and a GET endpoint through your API's existing CQRS layers, with functional tests, and opens a pull request.

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

## What the agent does

The agent reads how a request moves through the solution before it adds one. In a solution like jasontaylordev/CleanArchitecture, `global.json` pins the .NET SDK at 10.0.402, `Directory.Packages.props` manages every package version centrally, and `src/` holds `Domain`, `Application`, `Infrastructure`, `Web`, `ServiceDefaults`, `Shared` and an Aspire `AppHost`. `Web/Endpoints/TodoLists.cs` is an `IEndpointGroup` whose `Map` calls `RequireAuthorization()` and registers handlers with the `MapGet` and `MapPost` helpers in `Web/Infrastructure/EndpointRouteBuilderExtensions.cs`, which name each endpoint after its method for the OpenAPI document. `Web/Infrastructure/WebApplicationExtensions.cs` mounts every group at `/api/{ClassName}`. `GetTodoLists` sends a `GetTodosQuery` through MediatR and returns `TypedResults.Ok`.

On the Application side, `TodoLists/Queries/GetTodos/GetTodos.cs` carries the `[Authorize]` attribute from `Application/Common/Security`, takes `IApplicationDbContext` and `IMapper`, and projects `TodoList` rows into `TodoListDto` with AutoMapper profiles nested in the DTOs. `Application/DependencyInjection.cs` wires MediatR with the logging, unhandled-exception, authorization, validation and performance behaviours, so a new query gets all five without extra code. `Domain/Entities/TodoItem.cs` has `Title`, `Note`, `Priority` as the `PriorityLevel` enum from None to High, `Done` and `ListId`, which are the columns a spreadsheet user expects.

The agent adds `TodoLists/Queries/ExportTodos/` with an `ExportTodosQuery(int ListId)` marked `[Authorize]`, a `TodoItemRecord` DTO with its own mapping profile, an `ExportTodosVm` carrying `FileName`, `ContentType` and `Content` bytes, and a validator requiring a positive id, following `CreateTodoListCommandValidator`. The handler loads the items with `AsNoTracking`, calls `Guard.Against.NotFound` as `DeleteTodoListCommandHandler` does when the list is missing, and hands the records to a new `ICsvFileBuilder` interface in `Application/Common/Interfaces`. The implementation lives in `Infrastructure/Files/CsvFileBuilder.cs` on the CsvHelper package, which the agent adds to `Directory.Packages.props` and references from `Infrastructure.csproj`, with a `ClassMap` that writes `Id`, `Title`, `Note`, `Priority` and `Done` in that order; `Infrastructure/DependencyInjection.cs` registers it as transient next to `IIdentityService`. In `Web/Endpoints/TodoLists.cs` a `GetTodoListExport` handler on `{id}/export` returns `TypedResults.File` with the bytes, `text/csv` and a file name, annotated with `EndpointSummary` and `EndpointDescription` like its neighbours.

Tests follow `tests/Application.FunctionalTests/TodoLists/Queries/GetTodosTests.cs`: an `ExportTodosTests` class on `TestBase` calls `TestApp.RunAsDefaultUserAsync`, seeds a list with `TestApp.AddAsync`, sends the query with `TestApp.SendAsync`, and asserts with Shouldly that the content starts with the header row and has one line per item; a second test sends the query anonymously and expects `UnauthorizedAccessException`, and a third uses an unknown id and expects the not-found exception. `FunctionalTestSetup` starts the `TestAppHost` through `Aspire.Hosting.Testing` and resets the database with Respawn between tests, so the agent runs `dotnet build` and `dotnet test tests/Application.FunctionalTests` as `build.yml` does, then starts the API through the AppHost, signs in with the identity cookie flow in `Web.http`, and fetches the export with `curl` to keep the headers and the first lines.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a CSV export of a todo list's items to this API and open a pull request. Read global.json, Directory.Packages.props, src/Web/Endpoints/TodoLists.cs, src/Web/Infrastructure/EndpointRouteBuilderExtensions.cs, src/Web/Infrastructure/WebApplicationExtensions.cs, src/Application/TodoLists/Queries/GetTodos/GetTodos.cs, src/Application/TodoLists/Commands/DeleteTodoList/DeleteTodoList.cs, src/Application/Common/Interfaces/IApplicationDbContext.cs, src/Infrastructure/DependencyInjection.cs, src/Domain/Entities/TodoItem.cs, tests/Application.FunctionalTests/TodoLists/Queries/GetTodosTests.cs and tests/Application.FunctionalTests/Infrastructure/TestApp.cs first. In Application add TodoLists/Queries/ExportTodos with an ExportTodosQuery(int ListId) marked [Authorize], a TodoItemRecord DTO with an AutoMapper profile, an ExportTodosVm with FileName, ContentType and Content, a validator requiring ListId greater than zero, and a handler that loads the list's items with AsNoTracking, uses Guard.Against.NotFound for a missing list, and calls a new ICsvFileBuilder interface. Add CsvHelper to Directory.Packages.props and Infrastructure.csproj, implement CsvFileBuilder under src/Infrastructure/Files with a ClassMap writing Id, Title, Note, Priority and Done, and register it in AddInfrastructureServices. In Web/Endpoints/TodoLists.cs add GetTodoListExport on the pattern {id}/export returning TypedResults.File with text/csv, with EndpointSummary and EndpointDescription attributes. Add tests/Application.FunctionalTests/TodoLists/Queries/ExportTodosTests.cs with tests for the header row and item count, the anonymous refusal and the unknown id, in the style of GetTodosTests. Run dotnet build and dotnet test tests/Application.FunctionalTests, then start the API through the AppHost, sign in as Web.http shows and fetch the export with curl -i. Paste the test summary and the curl output in the pull request. Do not change the existing queries, commands or client apps.",
  "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 that touches each layer once: the `ExportTodos` folder in Application with the query, DTO, view model, validator and handler; `ICsvFileBuilder` in `Application/Common/Interfaces`; `CsvFileBuilder` and its class map under `Infrastructure/Files` plus one registration line in `Infrastructure/DependencyInjection.cs`; the CsvHelper line in `Directory.Packages.props` and `Infrastructure.csproj`; one new handler in `Web/Endpoints/TodoLists.cs`; and `ExportTodosTests.cs`. The description pastes the `dotnet test` summary and a `curl -i` of `/api/TodoLists/1/export` showing `Content-Type: text/csv`, the attachment file name and the first lines of the file.

The `build.yml` workflow restores, builds in Release and runs `dotnet test --no-build` on the pull request, so the new functional tests run beside the existing ones, and the OpenAPI document gains a `GetTodoListExport` operation that the Scalar page at `/scalar` shows without any further change.

A reviewer checks that the query carries `[Authorize]` so the authorization behaviour refuses an anonymous caller, that the handler reads with `AsNoTracking` and never loads lists the id does not match, that the CSV writer quotes a `Note` containing commas or newlines, and that the export of an empty list returns the header row alone rather than an error.

## Run it on every export request from a customer

A team that adds exports as customers ask for them starts one run per request with `POST /o/{org}/sessions`, this prompt with the entity and columns swapped in, and the repository in `resources`. The agent follows the same folder layout each time, so a `TodoLists` export and a later `Users` export look alike in review. Send a `request_id` with each call so a retried request returns the run it already started.

The key's `webhook_url` receives `run.completed` when the turn ends, with `data.session_url` for the pull request, so the ticket that asked for the export can be updated with the link.

## Why run it on Rush?

A clean architecture solution asks for five small files in the right places, and a change that skips the validator or registers the builder in the wrong project passes a build and fails review. In a Rush sandbox the agent reads the existing query and command as the pattern, runs the functional tests that start the Aspire host and reset the database, and fetches the file over HTTP, so the pull request shows the export working rather than compiling.

The transcript keeps the `dotnet test` output and the `curl` headers, and the same request produces the same layout on every API the team builds from this template, each in its own sandbox.

## Frequently asked questions

### Why go through MediatR instead of writing the CSV in the endpoint?

Because `Application/DependencyInjection.cs` attaches authorization, validation, logging and performance behaviours to every request, and `Web/Endpoints` classes only translate HTTP to a query. A query marked `[Authorize]` is refused for an anonymous caller before any code runs, and the functional tests can send it without an HTTP client.

### Why CsvHelper rather than string joins?

A `Note` field can contain commas, quotes and newlines, and a hand-written join produces a file spreadsheets open wrong. CsvHelper quotes those values by the RFC rules and the `ClassMap` fixes the column order, and the package version is pinned once in `Directory.Packages.props` like every other dependency.

### What does an unknown list id return?

The handler calls `Guard.Against.NotFound`, the same guard `DeleteTodoListCommandHandler` uses, and the `ProblemDetailsExceptionHandler` already registered in `Web/DependencyInjection.cs` turns it into a problem-details answer. One of the new tests sends an id that does not exist and expects that exception.

### Does the SPA need changes?

No. The endpoint is added to the API only, and the Angular and React client apps under `src/Web` are not touched. A later run can add an Export button that links to `/api/TodoLists/{id}/export`, which works with the same identity cookie the clients already send.

## More ASP.NET Core jobs

- [Add Health Checks to an ASP.NET Core App from a Linear Issue](https://getrush.ai/run/add-health-checks/aspnet-core/)
- [Add OpenTelemetry Tracing to an ASP.NET Core API](https://getrush.ai/run/add-opentelemetry/aspnet-core/)
- [Add Rate Limiting to an ASP.NET Core API](https://getrush.ai/run/add-rate-limiting/aspnet-core/)

## The same job on other stacks

- [Add CSV Export to a Blazor Web App](https://getrush.ai/run/add-csv-export/blazor/)
- [Add CSV Export to a Django App from a Linear Issue](https://getrush.ai/run/add-csv-export/django/)
- [Add CSV Export to a Django REST Framework API](https://getrush.ai/run/add-csv-export/django-rest-framework/)

## 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/)
