ASP.NET Core
Trigger On
- working on ASP.NET Core apps, services, or middleware
- changing auth, routing, configuration, hosting, or deployment behavior
- deciding between ASP.NET Core sub-stacks such as Blazor, Minimal APIs, or controller APIs
- debugging request pipeline issues
- modernizing legacy ASP.NET to ASP.NET Core
Documentation
References
- patterns.md - Detailed middleware patterns, security patterns, configuration patterns, DI patterns, error handling patterns, and logging patterns
- anti-patterns.md - Common ASP.NET Core mistakes including HttpClient misuse, async anti-patterns, configuration errors, DI issues, middleware ordering problems, and security vulnerabilities
Workflow
Detect the real hosting shape first:
- top-level
Program.cs structure
- middleware order and registration
- auth model (Identity, JWT, OAuth, cookies)
- endpoint registrations and routing
Follow the correct middleware order:
ExceptionHandler → HttpsRedirection → Static Files → Routing
→ CORS → Authentication → Authorization → Rate Limiting
→ Response Caching → Custom Middleware → Endpoints
Use built-in patterns correctly:
- Prefer
IOptions<T> / IOptionsSnapshot<T> for configuration
- Use
ILogger<T> for structured logging
- Use
IHttpClientFactory for HTTP clients (never new HttpClient())
- Use
IHostedService / BackgroundService for background work
Route specialized work to specific skills:
- UI and components →
dotnet-blazor
- Real-time →
dotnet-signalr
- RPC →
dotnet-grpc
- New HTTP APIs →
dotnet-minimal-apis (prefer unless controllers needed)
- Controller APIs →
dotnet-web-api
Validate with build, tests, and targeted endpoint checks.
Middleware Patterns
Correct Order Matters
var app = builder.Build();
app.UseExceptionHandler("/error"); // 1. Catch all exceptions
app.UseHsts(); // 2. Security headers
app.UseHttpsRedirection(); // 3. HTTPS redirect
app.UseStaticFiles(); // 4. Serve static files
app.UseRouting(); // 5. Route matching
app.UseCors(); // 6. CORS policy
app.UseAuthentication(); // 7. Who are you?
app.UseAuthorization(); // 8. Can you access?
app.UseRateLimiter(); // 9. Rate limiting
app.UseResponseCaching(); // 10. Response cache
app.MapControllers(); // 11. Endpoints
Custom Middleware Pattern
public class RequestTimingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestTimingMiddleware> _logger;
public RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var sw = Stopwatch.StartNew();
await _next(context);
_logger.LogInformation("Request {Path} completed in {Elapsed}ms",
context.Request.Path, sw.ElapsedMilliseconds);
}
}
Configuration Patterns
Strongly-Typed Options
// appsettings.json
{
"EmailSettings": {
"SmtpServer": "smtp.example.com",
"Port": 587
}
}
// Registration
builder.Services.Configure<EmailSettings>(
builder.Configuration.GetSection("EmailSettings"));
// Usage
public class EmailService(IOptions<EmailSettings> options)
{
private readonly EmailSettings _settings = options.Value;
}
Environment-Based Configuration
builder.Configuration
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.AddUserSecrets<Program>(optional: true);
Security Patterns
Authentication Setup
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
};
});
Authorization Policies
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy =>
policy.RequireRole("Admin"));
options.AddPolicy("MinAge18", policy =>
policy.RequireClaim("Age", "18", "19", "20")); // simplified
});
Anti-Patterns to Avoid
| Anti-Pattern |
Why It's Bad |
Better Approach |
new HttpClient() |
Socket exhaustion |
IHttpClientFactory |
Sync-over-async (Task.Result) |
Thread pool starvation |
await properly |
Storing secrets in appsettings.json |
Security risk |
User Secrets, Key Vault |
| Catching all exceptions silently |
Hides bugs |
Use IExceptionHandler |
async void in middleware |
Crashes process |
async Task |
| Missing HTTPS redirect |
Security risk |
UseHttpsRedirection() |
Performance Best Practices
- Use async/await everywhere — avoid sync blocking calls
- Pool DbContext properly — use scoped lifetime
- Enable response compression —
UseResponseCompression()
- Use output caching —
UseOutputCache() for .NET 7+
- Profile with diagnostic tools — Visual Studio Diagnostic Tools, PerfView
- Avoid allocations in hot paths — use
Span<T>, pooling
Deliver
- production-credible ASP.NET Core code and config
- a clear request pipeline and hosting story
- verification that matches the affected endpoints and middleware
- security headers and HTTPS configured correctly
Validate
- middleware order is intentional and documented
- security and configuration changes are explicit
- endpoint behavior is covered by tests or smoke checks
- no blocking calls in async context
- secrets are not committed to source control
- health checks are implemented for production readiness
1---
2name: dotnet-aspnet-core
3version: "1.0.0"
4category: "Web"
5description: "Build, debug, modernize, or review ASP.NET Core applications with correct hosting, middleware, security, configuration, logging, and deployment patterns on current .NET."
6compatibility: "Requires an ASP.NET Core project or solution."
7metadata:
8 source: https://skillmd.com/skills/aibot88/dotnet-aspnet-core
9---
10
11# ASP.NET Core
12
13## Trigger On
14
15- working on ASP.NET Core apps, services, or middleware
16- changing auth, routing, configuration, hosting, or deployment behavior
17- deciding between ASP.NET Core sub-stacks such as Blazor, Minimal APIs, or controller APIs
18- debugging request pipeline issues
19- modernizing legacy ASP.NET to ASP.NET Core
20
21## Documentation
22
23- [ASP.NET Core Overview](https://learn.microsoft.com/en-us/aspnet/core/?view=aspnetcore-10.0)
24- [ASP.NET Core Middleware](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-10.0)
25- [ASP.NET Core Best Practices](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/best-practices?view=aspnetcore-10.0)
26- [Configuration in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-10.0)
27- [Authentication and Authorization](https://learn.microsoft.com/en-us/aspnet/core/security/?view=aspnetcore-10.0)
28
29### References
30
31- [patterns.md](references/patterns.md) - Detailed middleware patterns, security patterns, configuration patterns, DI patterns, error handling patterns, and logging patterns
32- [anti-patterns.md](references/anti-patterns.md) - Common ASP.NET Core mistakes including HttpClient misuse, async anti-patterns, configuration errors, DI issues, middleware ordering problems, and security vulnerabilities
33
34## Workflow
35
361. **Detect the real hosting shape first:**
37 - top-level `Program.cs` structure
38 - middleware order and registration
39 - auth model (Identity, JWT, OAuth, cookies)
40 - endpoint registrations and routing
41
422. **Follow the correct middleware order:**
43 ```
44 ExceptionHandler → HttpsRedirection → Static Files → Routing
45 → CORS → Authentication → Authorization → Rate Limiting
46 → Response Caching → Custom Middleware → Endpoints
47 ```
48
493. **Use built-in patterns correctly:**
50 - Prefer `IOptions<T>` / `IOptionsSnapshot<T>` for configuration
51 - Use `ILogger<T>` for structured logging
52 - Use `IHttpClientFactory` for HTTP clients (never `new HttpClient()`)
53 - Use `IHostedService` / `BackgroundService` for background work
54
554. **Route specialized work to specific skills:**
56 - UI and components → `dotnet-blazor`
57 - Real-time → `dotnet-signalr`
58 - RPC → `dotnet-grpc`
59 - New HTTP APIs → `dotnet-minimal-apis` (prefer unless controllers needed)
60 - Controller APIs → `dotnet-web-api`
61
625. **Validate with build, tests, and targeted endpoint checks.**
63
64## Middleware Patterns
65
66### Correct Order Matters
67```csharp
68var app = builder.Build();
69
70app.UseExceptionHandler("/error"); // 1. Catch all exceptions
71app.UseHsts(); // 2. Security headers
72app.UseHttpsRedirection(); // 3. HTTPS redirect
73app.UseStaticFiles(); // 4. Serve static files
74app.UseRouting(); // 5. Route matching
75app.UseCors(); // 6. CORS policy
76app.UseAuthentication(); // 7. Who are you?
77app.UseAuthorization(); // 8. Can you access?
78app.UseRateLimiter(); // 9. Rate limiting
79app.UseResponseCaching(); // 10. Response cache
80app.MapControllers(); // 11. Endpoints
81```
82
83### Custom Middleware Pattern
84```csharp
85public class RequestTimingMiddleware
86{
87 private readonly RequestDelegate _next;
88 private readonly ILogger<RequestTimingMiddleware> _logger;
89
90 public RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> logger)
91 {
92 _next = next;
93 _logger = logger;
94 }
95
96 public async Task InvokeAsync(HttpContext context)
97 {
98 var sw = Stopwatch.StartNew();
99 await _next(context);
100 _logger.LogInformation("Request {Path} completed in {Elapsed}ms",
101 context.Request.Path, sw.ElapsedMilliseconds);
102 }
103}
104```
105
106## Configuration Patterns
107
108### Strongly-Typed Options
109```csharp
110// appsettings.json
111{
112 "EmailSettings": {
113 "SmtpServer": "smtp.example.com",
114 "Port": 587
115 }
116}
117
118// Registration
119builder.Services.Configure<EmailSettings>(
120 builder.Configuration.GetSection("EmailSettings"));
121
122// Usage
123public class EmailService(IOptions<EmailSettings> options)
124{
125 private readonly EmailSettings _settings = options.Value;
126}
127```
128
129### Environment-Based Configuration
130```csharp
131builder.Configuration
132 .AddJsonFile("appsettings.json", optional: false)
133 .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
134 .AddEnvironmentVariables()
135 .AddUserSecrets<Program>(optional: true);
136```
137
138## Security Patterns
139
140### Authentication Setup
141```csharp
142builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
143 .AddJwtBearer(options =>
144 {
145 options.TokenValidationParameters = new TokenValidationParameters
146 {
147 ValidateIssuer = true,
148 ValidateAudience = true,
149 ValidateLifetime = true,
150 ValidateIssuerSigningKey = true,
151 ValidIssuer = builder.Configuration["Jwt:Issuer"],
152 ValidAudience = builder.Configuration["Jwt:Audience"],
153 IssuerSigningKey = new SymmetricSecurityKey(
154 Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
155 };
156 });
157```
158
159### Authorization Policies
160```csharp
161builder.Services.AddAuthorization(options =>
162{
163 options.AddPolicy("AdminOnly", policy =>
164 policy.RequireRole("Admin"));
165 options.AddPolicy("MinAge18", policy =>
166 policy.RequireClaim("Age", "18", "19", "20")); // simplified
167});
168```
169
170## Anti-Patterns to Avoid
171
172| Anti-Pattern | Why It's Bad | Better Approach |
173|--------------|--------------|-----------------|
174| `new HttpClient()` | Socket exhaustion | `IHttpClientFactory` |
175| Sync-over-async (`Task.Result`) | Thread pool starvation | `await` properly |
176| Storing secrets in `appsettings.json` | Security risk | User Secrets, Key Vault |
177| Catching all exceptions silently | Hides bugs | Use `IExceptionHandler` |
178| `async void` in middleware | Crashes process | `async Task` |
179| Missing HTTPS redirect | Security risk | `UseHttpsRedirection()` |
180
181## Performance Best Practices
182
1831. **Use async/await everywhere** — avoid sync blocking calls
1842. **Pool DbContext properly** — use scoped lifetime
1853. **Enable response compression** — `UseResponseCompression()`
1864. **Use output caching** — `UseOutputCache()` for .NET 7+
1875. **Profile with diagnostic tools** — Visual Studio Diagnostic Tools, PerfView
1886. **Avoid allocations in hot paths** — use `Span<T>`, pooling
189
190## Deliver
191
192- production-credible ASP.NET Core code and config
193- a clear request pipeline and hosting story
194- verification that matches the affected endpoints and middleware
195- security headers and HTTPS configured correctly
196
197## Validate
198
199- middleware order is intentional and documented
200- security and configuration changes are explicit
201- endpoint behavior is covered by tests or smoke checks
202- no blocking calls in async context
203- secrets are not committed to source control
204- health checks are implemented for production readiness