home / skills / yldgio / codereview-skills / dotnet

dotnet skill

/skills/dotnet

This skill helps ensure robust ASP.NET Core apps by applying security, dependency injection, async/await patterns, and middleware best practices.

npx playbooks add skill yldgio/codereview-skills --skill dotnet

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
3.6 KB
---
name: dotnet
description: ASP.NET Core patterns, dependency injection, middleware, async/await, and security
---

## .NET Code Review Rules

### Security (Critical)
- Use `[Authorize]` attribute with policies
- Validate anti-forgery tokens for forms
- Use parameterized queries (EF Core does this by default)
- Don't log sensitive data
- Use HTTPS redirection middleware
- Store secrets in Azure Key Vault or environment variables
- Use User Secrets for local development
- Never commit secrets to source control
- Validate and sanitize all user input to prevent injection attacks
- Avoid storing sensitive data or security-relevant instructions in HTML comments

### Dependency Injection
- Register services with appropriate lifetime:
  - `Singleton`: stateless, thread-safe services
  - `Scoped`: per-request services (DbContext, etc.)
  - `Transient`: lightweight, stateless services
- Avoid captive dependencies (Singleton depending on Scoped)
- Use `IOptions<T>` pattern for configuration

### Async/Await
- Use `async`/`await` for I/O-bound operations (database, HTTP calls, file system)
- Always pass `CancellationToken` and respect it
- Avoid `.Result` or `.Wait()` (causes deadlocks)
- Use `ConfigureAwait(false)` in library code

### Advanced Async Patterns
- Prefer `ValueTask` for hot paths that often complete synchronously

### Controllers
- Keep controllers thin (delegate to services)
- Use `[ApiController]` attribute for automatic model validation
- Return `ActionResult<T>` for type safety
- Use `[ProducesResponseType]` for API documentation
- Implement API versioning (URL, header, or query string)
- Use consistent versioning strategy across endpoints

### Middleware
- Order matters: add middleware in correct sequence
- Authentication before Authorization
- Error handling middleware should be first (to catch all exceptions)
- Use `app.UseExceptionHandler()` for production error handling

### Model Validation
- Use Data Annotations or FluentValidation
- Validate at API boundary, not deep in business logic
- Return `400 Bad Request` for validation failures
- Include validation errors in response body

### Entity Framework Core (Essential)
- Use `AsNoTracking()` for read-only queries
- Avoid N+1 queries (use `Include()` or projection)
- Use migrations for schema changes
- Don't expose entities directly (use DTOs)
- Manage DbContext lifetime properly (scoped per request)
- Use async methods for database operations

### Advanced EF Core Patterns
- Use compiled queries for hot paths that execute frequently
- Use raw SQL via `FromSqlInterpolated`/`ExecuteSqlInterpolated` for complex queries while keeping parameters parameterized
- Define global query filters for concerns like soft deletes or multi-tenancy
- Consider splitting DbContexts by bounded context to keep models focused and reduce migration complexity

### Logging and Exception Handling
- Use structured logging with `ILogger<T>`
- Include correlation IDs for request tracing
- Log exceptions at appropriate levels (Error, Warning, Information)
- Use centralized exception handling middleware
- Don't catch exceptions unless you can handle them
- Include relevant context in log messages

### Thread Safety
- Singleton services must be thread-safe
- Avoid mutable shared state in singletons
- Use `lock`, `SemaphoreSlim`, or `ConcurrentDictionary` for shared resources
- Be cautious with static fields

### Testing
- Write unit tests for business logic
- Use in-memory providers for EF Core in tests
- Mock external dependencies with interfaces
- Test controller actions with integration tests
- Use `WebApplicationFactory` for integration testing

Overview

This skill provides concise, practical guidance for ASP.NET Core patterns covering dependency injection, middleware, async/await, EF Core, security, and testing. It focuses on actionable rules and patterns you can apply during code reviews or when designing services. The guidance emphasizes safety, performance, and maintainability for web APIs and backend services.

How this skill works

The skill inspects common .NET app areas and prescribes best practices: secure configuration and authentication, correct DI lifetimes, async patterns, middleware ordering, model validation, EF Core usage, logging, and testing approaches. It flags risky anti-patterns such as captive dependencies, blocking async calls, leaking entities, and improper middleware order. Recommendations are concrete and tied to typical implementation choices in ASP.NET Core.

When to use it

  • Performing code reviews for ASP.NET Core projects
  • Designing or refactoring service and controller layers
  • Auditing security, secrets, and authentication setups
  • Optimizing data access and EF Core queries
  • Establishing CI tests and integration testing practices

Best practices

  • Apply [Authorize] with explicit policies and validate anti-forgery tokens for form endpoints
  • Register services with appropriate lifetimes (Singleton, Scoped, Transient) and avoid captive dependencies
  • Use async/await for I/O, always accept CancellationToken, and never use .Result/.Wait() in async flows
  • Order middleware deliberately: exception handling first, authentication before authorization, and HTTPS redirection enabled
  • Use DTOs instead of exposing EF entities, Apply AsNoTracking() for read-only queries, and avoid N+1 by using Include or projection
  • Use structured logging (ILogger<T>), include correlation IDs, and centralize exception handling via middleware

Example use cases

  • A code review identifying a Singleton depending on a DbContext and recommending scoped lifetime changes
  • Refactoring controllers to be thin: move business logic into services and return ActionResult<T>
  • Hardening an app by adding HTTPS redirection, Azure Key Vault for secrets, and policy-based [Authorize] attributes
  • Improving performance by replacing blocking calls with async I/O, adding ConfigureAwait(false) in libraries, and using compiled EF Core queries for hot paths
  • Writing integration tests with WebApplicationFactory and using in-memory EF providers for unit tests

FAQ

How should secrets be stored during development and production?

Use User Secrets for local development and environment variables or Azure Key Vault in production. Never commit secrets to source control.

When should I use Scoped vs Singleton services?

Use Scoped for per-request dependencies like DbContext. Use Singleton only for stateless, thread-safe services. Avoid Singleton that depends on Scoped services to prevent captive dependency issues.