# Add OpenTelemetry Tracing to an ASP.NET Core API

Yes. An agent adds OpenTelemetry tracing for ASP.NET Core, EF Core and outgoing HTTP to your API with an OTLP exporter, updates the lock files, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-opentelemetry/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 the API is built and gated before it adds a package, because this kind of repository refuses a sloppy change at restore time. In an API shaped like realworld-apps/aspnetcore-realworld-example-app, `global.json` pins the SDK at `10.0.402` with `latestFeature` roll-forward, `Directory.Build.props` targets `net10.0` with nullable, `WarningsAsErrors`, `EnforceCodeStyleInBuild`, `ManagePackageVersionsCentrally` and `RestorePackagesWithLockFile` all on, and `Directory.Packages.props` holds every version, Serilog 4.4.0, `Swashbuckle.AspNetCore` 10.3.0, EF Core 10.0.13 for SQLite and SQL Server, Mediator 3.0.2. `src/Conduit/Program.cs` registers the database, localization, Swagger, CORS, controllers with the `api` route prefix convention, JWT and authorization, then `AddSerilogLogging` on the logger factory, the error middleware, routing, auth and `MapControllers`. There is no tracing and no `ActivitySource`.

The agent adds `OpenTelemetry.Extensions.Hosting`, `OpenTelemetry.Instrumentation.AspNetCore`, `OpenTelemetry.Instrumentation.Http`, `OpenTelemetry.Instrumentation.EntityFrameworkCore` and `OpenTelemetry.Exporter.OpenTelemetryProtocol` as `PackageVersion` entries in `Directory.Packages.props` and as version-less `PackageReference` entries in `src/Conduit/Conduit.csproj`, then runs `dotnet restore Conduit.slnx` without `--locked-mode` once so `packages.lock.json` records them, which is the step the `AGENTS.md` toolchain section says to include. The EF Core instrumentation is still a prerelease package, so its version carries the `beta` suffix and the pull request says so.

Wiring goes in `ServicesExtensions.cs` beside `AddConduit` and `AddJwt`: an `AddConduitTelemetry(this IServiceCollection, IConfiguration)` that calls `AddOpenTelemetry()`, sets the service name from `OTEL_SERVICE_NAME` with a fallback of `Conduit`, and adds ASP.NET Core, HTTP client and EF Core instrumentation plus the OTLP exporter, which reads `OTEL_EXPORTER_OTLP_ENDPOINT` from the environment on its own. The ASP.NET Core instrumentation is filtered so `/swagger` requests produce no spans. `Program.cs` gains one line calling it, placed before `builder.Build()`. Because `ErrorHandlingMiddleware` turns exceptions into RealWorld error bodies, the agent enriches the request span with the status code the middleware writes so failed requests are visible as failures.

The test joins `tests/Conduit.IntegrationTests`, where `ApiFactory` is a `WebApplicationFactory<Program>` on a temporary SQLite file. A new `TelemetryTests.cs` builds the factory, adds an in-memory exporter through the test host's service configuration, registers a user through `/api/users` the way `ApiTests.cs` does, and asserts one server span for `POST /api/users` with a `201` status and at least one EF Core span beneath it. The agent then runs the repository's own gate, `dotnet run --project build/build.csproj -- test`, which formats with CSharpier 1.3.0, builds in Release with locked restore and runs every test project, and runs `make test-hurl-with-managed-server` so the RealWorld spec suite still passes with tracing on.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add OpenTelemetry tracing to this ASP.NET Core API and open a pull request. Read AGENTS.md, global.json, Directory.Build.props, Directory.Packages.props, src/Conduit/Conduit.csproj, src/Conduit/Program.cs, src/Conduit/ServicesExtensions.cs, src/Conduit/Infrastructure/Errors/ErrorHandlingMiddleware.cs, tests/Conduit.IntegrationTests/ApiFactory.cs, tests/Conduit.IntegrationTests/ApiTests.cs, build/Program.cs and .github/workflows/dotnetcore.yml first. Add OpenTelemetry.Extensions.Hosting, OpenTelemetry.Instrumentation.AspNetCore, OpenTelemetry.Instrumentation.Http, OpenTelemetry.Instrumentation.EntityFrameworkCore and OpenTelemetry.Exporter.OpenTelemetryProtocol to Directory.Packages.props and reference them from Conduit.csproj without versions, then restore once without --locked-mode so every packages.lock.json is updated and commit those files. Add AddConduitTelemetry to ServicesExtensions.cs: service name from OTEL_SERVICE_NAME with a fallback of Conduit, ASP.NET Core instrumentation that skips /swagger, HTTP client and EF Core instrumentation, and the OTLP exporter configured from the environment. Call it from Program.cs before builder.Build(). Add tests/Conduit.IntegrationTests/TelemetryTests.cs that uses ApiFactory with an in-memory span exporter, registers a user through POST /api/users as ApiTests.cs does, and asserts a server span for that route with status 201 and an EF Core span beneath it. Run dotnet run --project build/build.csproj -- test and make test-hurl-with-managed-server, fix anything they report including formatting and analyzer warnings, and paste the output in the pull request description. Do not change any feature, migration or the realworld submodule.",
  "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 with five new `PackageVersion` lines in `Directory.Packages.props`, five `PackageReference` lines in `src/Conduit/Conduit.csproj`, the updated `packages.lock.json` files, `AddConduitTelemetry` in `ServicesExtensions.cs`, one line in `Program.cs`, and `TelemetryTests.cs`. The description shows the output of the build runner's `test` target, the Hurl suite summary, and a console-exported trace from one `POST /api/users` in the sandbox with the request span and the SQLite insert beneath it.

The repository's `Build and Test` workflow runs `dotnet restore Conduit.slnx --locked-mode` and the build runner with `--check-format` on the pull request, so a lock file the agent forgot would fail there, and the `RealWorld API Tests` workflow runs Hurl and Bruno against the managed server. The agent pushes one commit for packages and lock files, one for the wiring, and one for the test.

A reviewer checks that the prerelease EF Core instrumentation version is acceptable to them, that `/swagger` is filtered, that the exporter stays quiet when `OTEL_EXPORTER_OTLP_ENDPOINT` is unset, and that the warnings-as-errors build is clean. Then they set the endpoint in their deployment's environment.

## Run it on every service without tracing

A team moving every .NET service onto one collector starts one run per repository with `POST /o/{org}/sessions`, this prompt and the repository in `resources`. The agent reads each service's own project files, so one without central package management gets versions in its `csproj` and one on SQL Server gets the same EF Core instrumentation over its provider, and each run opens its own pull request.

The key's `webhook_url` receives `run.completed` for each run with a `session_url`, so a script can post the pull request links to the team channel as they land.

## Why run it on Rush?

The registration is a dozen lines; the friction is everything around it in a repository with locked restores, central versions, CSharpier and warnings as errors, where the first push usually fails on a lock file or a formatting diff rather than on tracing. In a Rush sandbox the agent runs the same build runner CI runs, fixes what it reports, and the output is kept in the transcript with a real exported trace, so the pull request arrives green rather than after three rounds.

The change lands where the repository's own `AGENTS.md` says such things go, in `ServicesExtensions.cs` with an integration test beside `ApiTests.cs`, and the same request works unchanged across every ASP.NET Core service the team owns.

## Frequently asked questions

### Why do the lock files change?

`Directory.Build.props` sets `RestorePackagesWithLockFile`, and CI restores with `--locked-mode`, which fails when `packages.lock.json` does not match the references. Adding a package therefore needs one restore without `--locked-mode` and the resulting lock file changes committed, which `AGENTS.md` asks for explicitly.

### Is the EF Core instrumentation stable?

The package is still published as a prerelease with a `beta` suffix, while the hosting, ASP.NET Core, HTTP and OTLP packages are stable releases. The pull request names the exact version it pinned so a reviewer can decide whether to keep it or trace only HTTP for now.

### Does it slow down the Hurl and Bruno suites?

The agent runs `make test-hurl-with-managed-server` with tracing on and no exporter endpoint, and pastes the summary. The instrumentation creates activities in process; with no endpoint set the OTLP exporter has nothing to send to.

### Will Serilog still work?

Yes. `AddSerilogLogging` on the logger factory is untouched; tracing is added through `AddOpenTelemetry()` on the service collection and does not replace logging. Correlating log lines with trace ids is a follow-up noted in the pull request.

## More ASP.NET Core jobs

- [Add Rate Limiting to an ASP.NET Core API](https://getrush.ai/run/add-rate-limiting/aspnet-core/)
- [Add Soft Delete to an ASP.NET Core App](https://getrush.ai/run/add-soft-delete/aspnet-core/)
- [List Every API Endpoint in an ASP.NET Core App](https://getrush.ai/run/api-endpoint-inventory/aspnet-core/)

## The same job on other stacks

- [Add OpenTelemetry Tracing to a chi API](https://getrush.ai/run/add-opentelemetry/chi/)
- [Add OpenTelemetry Tracing to a Django REST Framework API](https://getrush.ai/run/add-opentelemetry/django-rest-framework/)
- [Add OpenTelemetry Tracing to an Echo API](https://getrush.ai/run/add-opentelemetry/echo/)

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