Skip to content

project rulesBackend and APIsdotnetcsharp

ASP.NET Core Web API Rules

Project rules for ASP.NET Core APIs, minimal APIs or controllers: DTOs, async all the way, ProblemDetails errors and EF Core discipline.

npx workspacetemplates add dotnet-webapi-rules --tool claude-code

Writes 1 file to your project root

CLAUDE.mdadd to your file22 lines · 1.4 KBFile
# Project rules: ASP.NET Core Web API

## Structure
- Pick one style per project: minimal APIs grouped with `MapGroup` and one static class per feature, or controllers with `[ApiController]`. Do not mix them.
- Enable nullable reference types and treat warnings as errors. Use `record` types for DTOs.
- Never return or accept EF entities in endpoints. Map to request and response DTOs explicitly.

## Async and DI
- Async all the way: `async Task<T>`, pass the `CancellationToken` to every I/O call. Never call `.Result` or `.Wait()`.
- Register services with the narrowest lifetime. Use `IOptions<T>` with validation on start for settings. Secrets come from user secrets or the environment, never from appsettings in git.

## Data
- Use `AsNoTracking()` for reads. Project with `Select` instead of loading whole graphs. Avoid N+1 by using `Include` or projection.
- Schema changes only through EF migrations; review the generated SQL.

## Errors and validation
- Validate input with FluentValidation or data annotations before the handler runs. Return `ProblemDetails` through `AddProblemDetails()` and an exception handler; never expose exception messages.
- Return correct status codes: 201 with Location, 204, 404, 409, 422.

## Quality
- Version public routes. Document with OpenAPI and `Produces` metadata.
- Test with `WebApplicationFactory`. Run `dotnet build`, `dotnet test` and `dotnet format --verify-no-changes` before finishing.

What it does

These rules keep an ASP.NET Core API consistent whether you use minimal APIs or controllers. They decide where validation, mapping and data access live, so generated endpoints follow one shape.

They also set the habits that prevent common production problems: blocking async calls, tracked queries that bloat memory and exceptions that leak internals to clients.

Example

you › Add an endpoint to cancel an order

agent › The agent adds POST /orders/{id}/cancel in the orders feature group, validates state, uses a cancellation token, returns ProblemDetails with 409 if already shipped, and adds a WebApplicationFactory test.

Questions

Should I choose minimal APIs or controllers?
Either is fine. The rule is to choose one and stay with it, so the agent never mixes two patterns.
Does it cover authentication?
Only the secrets and error rules. Add your identity provider details to the file for auth conventions.
  • Django Rules

    Project rulespython

    Free
  • Flask Rules

    Project rulespython

    Free
  • Go Service Rules

    Project rulesgo

    Free
  • GraphQL API Rules

    Project rulesgraphql

    Free