ASP.NET Core Cookbook
“How would you do X?” — practical, production-ready recipes with the approach, full code, pitfalls and variations.
ASP.NET Core
- Accept file uploads with size and type limitsUploads can fill the disk, overwrite files or carry the wrong content.
- Add OpenTelemetry traces and metricsLatency spikes and errors can't be traced across services and dependencies.
- Apply EF Core migrations safely during deploymentCalling Database.Migrate() at startup races between instances and needs schema permissions in the app.
- Bind and validate options at startupA missing or invalid setting only shows up when the code path runs in production.
- Cache responses with output caching and evict by tagPopular GET endpoints hit the database on every request, and cached data must refresh after edits.
- Call external APIs with typed HttpClients and resilienceOutbound calls exhaust sockets, have no timeouts, and fail on transient errors.
- Configure CORS for a browser front endThe SPA on another origin can't call the API, and someone suggests allowing every origin.
- Expose liveness and readiness health checksOrchestrators restart healthy pods or route traffic to instances whose database is down.
- Generate OpenAPI documents with Microsoft.AspNetCore.OpenApiAPI consumers need an accurate, up-to-date contract with auth requirements and examples.
- Handle concurrent updates with concurrency tokensTwo admins edit the same record and the second save silently overwrites the first.
- Map exceptions to ProblemDetails with IExceptionHandlerUnhandled exceptions leak stack traces, and domain errors all become 500s.
- Organize minimal API endpoints into groupsProgram.cs grows into hundreds of lines of endpoints with repeated prefixes, auth and tags.
- Protect APIs with JWT bearer tokens and policiesThe API must accept access tokens from an identity provider and enforce scopes and roles.
- Publish a container image without a DockerfileMaintaining Dockerfiles for many services is repetitive, and images run as root.
- Rate limit per user and per IPA single client can exhaust the API, and login endpoints are brute-forced.
- Run periodic background work with scoped servicesA background job needs the DbContext (scoped) and must stop cleanly on shutdown.
- Speed up EF Core reads with projections, no-tracking and poolingList endpoints load whole entity graphs, track them for no reason and run slowly under load.
- Stream updates to browsers with Server-Sent EventsThe UI polls every second for order status updates.
- Validate minimal API input with AddValidationHandlers start with lines of manual `if` checks and return inconsistent error formats.
- Write integration tests with WebApplicationFactoryUnit tests pass but routing, auth, validation and serialization bugs reach production.