Complete AI prompt library for .NET developers. Covers Minimal APIs and Controllers, Entity Framework Core, JWT authentication with ASP.NET Identity, MediatR CQRS pattern, xUnit testing, Azure deployment, and performance with output caching.
ASP.NET Core in 2026: Microsoft's High-Performance Web Framework
.NET 9 with ASP.NET Core delivers some of the highest throughput numbers in the web framework benchmarks. C# 13, Primary Constructors, Minimal APIs, and Native AOT compilation make it a compelling choice for high-performance microservices. The key to productive AI prompting for .NET is specifying the modern patterns โ Minimal APIs, MediatR CQRS, Result pattern, and EF Core 9 โ rather than the MVC + DataAnnotations approach from .NET Framework era.
1. Minimal API with CQRS via MediatR
You are a senior .NET 9 architect using C# 13.
Build a complete Task API using ASP.NET Core Minimal APIs with MediatR CQRS pattern:
Endpoint registration (TaskEndpoints.cs โ extension method on WebApplication):
- GET /api/v1/tasks โ GetTasksQuery
- GET /api/v1/tasks/{id:guid} โ GetTaskByIdQuery
- POST /api/v1/tasks โ CreateTaskCommand
- PUT /api/v1/tasks/{id:guid} โ UpdateTaskCommand
- DELETE /api/v1/tasks/{id:guid} โ DeleteTaskCommand
Each endpoint:
- [Authorize] attribute or RequireAuthorization() with policy name
- Extract organizationId from JWT claims (ClaimsPrincipal extension method)
- Send to IMediator.Send()
- Return TypedResults (Results<Ok<TaskDto>, NotFound, ForbidHttpResult, ValidationProblem>)
Commands/Queries (records):
- GetTasksQuery(Guid OrganizationId, TaskStatus? Status, int Page, int PageSize) : IRequest<PagedResult<TaskDto>>
- CreateTaskCommand(string Title, string? Description, DateOnly? DueDate, Guid ProjectId, Guid OrganizationId) : IRequest<Result<TaskDto>>
Result pattern: Result<T> with IsSuccess, Value, Error (no exceptions for expected failures).
Output: endpoint registration, commands/queries as records, handlers, and Program.cs registration.
2. Entity Framework Core 9 Configuration
You are an EF Core 9 expert.
Design EF Core 9 entity configurations for a multi-tenant task management system:
Entities (C# 13 primary constructors):
- Organization, User, Project, Task, Comment, AuditLog
IEntityTypeConfiguration<Task> (TaskConfiguration : IEntityTypeConfiguration<Task>):
- Table name, schema: tasks schema
- Primary key: Guid (NewId() from UlidId or sequential GUID for index friendliness)
- Soft delete: IsDeleted (bool) + DeletedAt (DateTime?) with global query filter
- Tenant filter: global query filter for OrganizationId == currentTenantId (injected via ITenantContext)
- Indexes: composite [OrganizationId, Status, DueDate], [OrganizationId, AssignedToId]
- Value conversions: TaskStatus enum โ string (not int for readability in DB)
- Owned entity: Task.Address as owned type (no separate table)
- Concurrency: RowVersion byte[] property for optimistic concurrency
Bulk operations (EF Core 7+):
- ExecuteUpdateAsync for bulk status changes (no entity loading)
- ExecuteDeleteAsync for hard delete admin operations
Repository:
- ITaskRepository with async methods, CancellationToken on all
- Specification pattern: ISpecification<T> for reusable query building
Output: entity configurations, DbContext with all entity registrations, repository interface + EF implementation.
3. JWT Authentication with ASP.NET Identity
You are a .NET security engineer.
Implement JWT authentication for ASP.NET Core 9 with ASP.NET Identity:
Identity configuration:
- ApplicationUser extends IdentityUser with: OrganizationId (Guid), Role (enum), CreatedAt, LastLoginAt
- IdentityOptions: strong password policy, lockout after 5 failures for 15 minutes, require confirmed email
JWT setup (Program.cs):
- AddAuthentication().AddJwtBearer() with RSA256 (load public key from env for validation)
- Token issuer: separate TokenService
- Validate: issuer, audience, lifetime, signing key
TokenService:
- GenerateAccessToken(ApplicationUser user): RS256, 15-minute lifetime, claims: sub, email, organizationId, role, jti
- GenerateRefreshToken(): opaque 32-byte random, stored in RefreshTokens table with userId, expiresAt, isRevoked
- RevokeRefreshToken(token): mark as revoked, optional: revoke entire family on reuse detection
- RefreshAccessToken(refreshToken): validate table entry โ generate new access token + rotate refresh token
Auth endpoints (/api/auth):
- POST /login: Identity SignInManager, return token pair
- POST /refresh: validate refresh token table
- POST /logout: revoke refresh token
- POST /register: create user, send confirmation email via IEmailSender
Output: TokenService, AuthController (or Minimal API), Identity configuration in Program.cs.
4. MediatR Pipeline Behaviors
You are a MediatR expert for .NET applications.
Build a production MediatR pipeline with behaviors (in execution order):
1. LoggingBehavior<TRequest, TResponse>:
- Log: request type, request payload (sanitize sensitive fields), duration, user ID from ICurrentUser
- Structured logging with Serilog: include correlationId, userId, organizationId as enrichers
- Warn if handler takes longer than 500ms
2. ValidationBehavior<TRequest, TResponse>:
- Run all IValidator<TRequest> registered via FluentValidation
- On failure: return Result.Failure with ValidationError list (not throw exception)
- Only run for commands (implement ICommand marker interface check)
3. AuthorizationBehavior<TRequest, TResponse>:
- Check IAuthorizeRequest on command/query
- Call IAuthorizationService with the required policy name
- Return Result.Failure(Error.Forbidden) if denied
4. TransactionBehavior<TRequest, TResponse>:
- Wrap commands (ICommand) in EF Core DbContext.BeginTransactionAsync
- Commit on success, rollback on exception
- Do NOT apply to queries
5. CachingBehavior<TRequest, TResponse>:
- For queries implementing ICacheable (with CacheKey and CacheDuration properties)
- Read from IDistributedCache, deserialize, return early if hit
- On miss: execute handler, write to cache
Output: all 5 behavior classes, ICurrentUser interface + HttpContext implementation, FluentValidation registration in Program.cs.
5. xUnit Integration Tests with WebApplicationFactory
You are a .NET testing expert.
Write integration tests for the Task API using xUnit and WebApplicationFactory:
Test infrastructure:
- CustomWebApplicationFactory<Program>: replace real DB with Testcontainers PostgreSQL, override JWT validation to accept test tokens
- DatabaseFixture: IAsyncLifetime โ create schema on InitializeAsync, truncate tables between tests
- TestJwtTokenFactory: generate signed JWT with any claims for test users
- ApiClient: HttpClient wrapper with typed methods (GetTaskAsync, CreateTaskAsync, etc.)
Test cases (Fact and Theory):
[Fact] CreateTask_WithValidData_Returns201AndCreatedTask
[Fact] CreateTask_AsMemberOfDifferentOrg_Returns403
[Theory, InlineData("", "Title required"), InlineData("ab", "Min 3 chars")]
CreateTask_WithInvalidTitle_Returns400WithFieldError(string title, string expectedMessage)
[Fact] GetTasks_ReturnsOnlyCurrentOrgTasks_TenantIsolation
[Fact] UpdateTask_WithStaleVersion_Returns409Conflict
[Fact] DeleteTask_SoftDeletes_NotReturnedInSubsequentGet
Assertions:
- HTTP status code (FluentAssertions: response.Should().HaveStatusCode(201))
- Response body JSON (deserialize to DTO, assert fields)
- Database state (inject IDbContextFactory, query DB directly to assert persistence)
Output: WebApplicationFactory, DatabaseFixture, test token factory, and all test cases.
6. Good vs Bad .NET Prompts
| Task | โ Bad Prompt | โ Good Prompt |
|---|---|---|
| API design | "Build a REST API in C#" | "Build ASP.NET Core 9 Minimal API for Task resource: MediatR commands/queries as C# 13 records, TypedResults return types, RequireAuthorization() per endpoint, extract OrganizationId from JWT claims, return ValidationProblem on FluentValidation failure. Result pattern for error handling." |
| EF Core | "Query tasks from database" | "Write EF Core 9 query for tasks: AsNoTracking() for read, Include(t => t.Assignee) + Include(t => t.Project), global query filter for soft delete + tenant isolation, ExecuteUpdateAsync for bulk status change. Add composite index [OrganizationId, Status, DueDate] in IEntityTypeConfiguration." |
| Testing | "Write unit tests for my API" | "Write xUnit integration tests with WebApplicationFactory: Testcontainers PostgreSQL, override JWT for test tokens, FluentAssertions, test tenant isolation (403 cross-org), test optimistic concurrency (409 on stale RowVersion), assert DB state via IDbContextFactory." |
Generate a custom .NET prompt โ Try PromptPrepare free
Found this helpful? Share it.