# Aspnet Core

> Build, debug, modernize, or review ASP.NET Core applications with correct hosting, middleware, security, configuration, logging, and deployment patterns on current .NET. USE FOR: working on ASP.NET Core apps, services, or middleware; changing auth, routing, configuration, hosting, or deployment behavior; deciding between ASP.NET Core sub-stacks. DO NOT USE FOR: unrelated stacks; generic tasks tha…

- **Type:** Skill
- **Install:** `agentstack add skill-managedcode-dotnet-skills-aspnet-core`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [managedcode](https://agentstack.voostack.com/s/managedcode)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [managedcode](https://github.com/managedcode)
- **Source:** https://github.com/managedcode/dotnet-skills/tree/main/catalog/Frameworks/ASP.NET-Core/skills/aspnet-core
- **Website:** https://skills.managed-code.com

## Install

```sh
agentstack add skill-managedcode-dotnet-skills-aspnet-core
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# 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

- [ASP.NET Core Overview](https://learn.microsoft.com/en-us/aspnet/core/?view=aspnetcore-10.0)
- [ASP.NET Core Middleware](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-10.0)
- [ASP.NET Core Best Practices](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/best-practices?view=aspnetcore-10.0)
- [Configuration in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-10.0)
- [Authentication and Authorization](https://learn.microsoft.com/en-us/aspnet/core/security/?view=aspnetcore-10.0)

### References

- [patterns.md](references/patterns.md) - Detailed middleware patterns, security patterns, configuration patterns, DI patterns, error handling patterns, and logging patterns
- [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

## Workflow

1. **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

2. **Follow the correct middleware order:**
   ```
   ExceptionHandler → HttpsRedirection → Static Files → Routing
   → CORS → Authentication → Authorization → Rate Limiting
   → Response Caching → Custom Middleware → Endpoints
   ```

3. **Use built-in patterns correctly:**
   - Prefer `IOptions` / `IOptionsSnapshot` for configuration
   - Use `ILogger` for structured logging
   - Use `IHttpClientFactory` for HTTP clients (never `new HttpClient()`)
   - Use `IHostedService` / `BackgroundService` for background work

4. **Route specialized work to specific skills:**
   - UI and components → `blazor`
   - Real-time → `signalr`
   - RPC → `grpc`
   - New HTTP APIs → `minimal-apis` (prefer unless controllers needed)
   - Controller APIs → `web-api`

5. **Validate with build, tests, and targeted endpoint checks.**

## Current Upstream Notes

- ASP.NET Core `v9.0.17` is a servicing release with branding and dependency updates rather than a new programming model. Keep existing middleware, hosting, and endpoint guidance intact, then rerun build/tests after package updates.
- The current Microsoft Learn overview for `aspnetcore-10.0` remains the routing entry point for choosing between Blazor, Minimal APIs, controller APIs, SignalR, and gRPC.

## Middleware Patterns

### Correct Order Matters
```csharp
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
```csharp
public class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public RequestTimingMiddleware(RequestDelegate next, ILogger 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
```csharp
// appsettings.json
{
  "EmailSettings": {
    "SmtpServer": "smtp.example.com",
    "Port": 587
  }
}

// Registration
builder.Services.Configure(
    builder.Configuration.GetSection("EmailSettings"));

// Usage
public class EmailService(IOptions options)
{
    private readonly EmailSettings _settings = options.Value;
}
```

### Environment-Based Configuration
```csharp
builder.Configuration
    .AddJsonFile("appsettings.json", optional: false)
    .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables()
    .AddUserSecrets(optional: true);
```

## Security Patterns

### Authentication Setup
```csharp
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
```csharp
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

1. **Use async/await everywhere** — avoid sync blocking calls
2. **Pool DbContext properly** — use scoped lifetime
3. **Enable response compression** — `UseResponseCompression()`
4. **Use output caching** — `UseOutputCache()` for .NET 7+
5. **Profile with diagnostic tools** — Visual Studio Diagnostic Tools, PerfView
6. **Avoid allocations in hot paths** — use `Span`, 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

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [managedcode](https://github.com/managedcode)
- **Source:** [managedcode/dotnet-skills](https://github.com/managedcode/dotnet-skills)
- **License:** MIT
- **Homepage:** https://skills.managed-code.com

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-managedcode-dotnet-skills-aspnet-core
- Seller: https://agentstack.voostack.com/s/managedcode
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
