aspnet-core

GitHub

提供 ASP.NET Core 应用开发、调试及现代化改造的指导,涵盖中间件配置、安全认证、路由部署等最佳实践与反模式。

catalog/Frameworks/ASP.NET-Core/skills/aspnet-core/SKILL.md managedcode/dotnet-skills

Trigger Scenarios

ASP.NET Core 应用或中间件开发 修改认证、路由或配置行为 排查请求管道问题 选择 Blazor 或 Minimal APIs 等子栈

Install

npx skills add managedcode/dotnet-skills --skill aspnet-core -g -y
More Options

Non-standard path

npx skills add https://github.com/managedcode/dotnet-skills/tree/main/catalog/Frameworks/ASP.NET-Core/skills/aspnet-core -g -y

Use without installing

npx skills use managedcode/dotnet-skills@aspnet-core

指定 Agent (Claude Code)

npx skills add managedcode/dotnet-skills --skill aspnet-core -a claude-code -g -y

安装 repo 全部 skill

npx skills add managedcode/dotnet-skills --all -g -y

预览 repo 内 skill

npx skills add managedcode/dotnet-skills --list

SKILL.md

Frontmatter
{
    "name": "aspnet-core",
    "description": "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 that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.",
    "compatibility": "Requires an ASP.NET Core project or solution."
}

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

  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<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
  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 v10.0.11 is a servicing release rather than a new programming model. It updates OpenAPI to 2.7.5, fixes restoration of expired client-persisted Blazor circuit state, and refreshes servicing dependencies. Keep the existing middleware and endpoint architecture, then rerun focused OpenAPI, interactive-rendering, auth, and startup tests.
  • The August 2026 Microsoft Learn overview for aspnetcore-10.0 remains the routing entry point for choosing between Blazor, Minimal APIs, controller APIs, SignalR, and gRPC; the refresh does not justify changing an existing app model by itself.

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

  1. Use async/await everywhere — avoid sync blocking calls
  2. Pool DbContext properly — use scoped lifetime
  3. Enable response compressionUseResponseCompression()
  4. Use output cachingUseOutputCache() for .NET 7+
  5. Profile with diagnostic tools — Visual Studio Diagnostic Tools, PerfView
  6. 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

Version History

  • 0559476 Current 2026-08-19 23:30

    更新 .NET v10.0.11 服务版本说明,同步 Microsoft Learn 最新文档链接。

  • 7ab7f03 2026-07-25 05:21

Same Skill Collection

catalog/Frameworks/gRPC/skills/grpc/SKILL.md
catalog/Frameworks/Official-Astro/skills/astro-developer/SKILL.md
catalog/Frameworks/Official-DotNet-ASPNetCore/skills/configuring-opentelemetry-dotnet/SKILL.md
catalog/Frameworks/Official-DotNet-ASPNetCore/skills/dotnet-webapi/SKILL.md
catalog/Frameworks/Official-DotNet-ASPNetCore/skills/minimal-api-file-upload/SKILL.md
catalog/Frameworks/Orleans/skills/orleans/SKILL.md
catalog/Frameworks/ThreeJS-WebGPU-TSL/skills/webgpu-threejs-tsl/SKILL.md
catalog/Libraries/Official-DotNet-Data/skills/optimizing-ef-core-queries/SKILL.md
catalog/Platform/Official-DotNet-Advanced/skills/csharp-scripts/SKILL.md
catalog/Platform/Official-DotNet-Advanced/skills/nuget-trusted-publishing/SKILL.md
catalog/Platform/Official-DotNet-Blazor/skills/create-blazor-project/SKILL.md
catalog/Platform/Official-DotNet-Blazor/skills/fetch-and-send-data/SKILL.md
catalog/Platform/Official-DotNet-Blazor/skills/support-prerendering/SKILL.md
catalog/Platform/Official-DotNet-Blazor/skills/use-js-interop/SKILL.md
catalog/Platform/Official-DotNet-Experimental/skills/exp-mock-usage-analysis/SKILL.md
catalog/Platform/Official-DotNet-Experimental/skills/exp-simd-vectorization/SKILL.md
catalog/Platform/Official-DotNet-Test-Migration/skills/migrate-xunit-to-mstest/SKILL.md
catalog/Platform/Official-DotNet-Test-Migration/skills/migrate-xunit-to-xunit-v3/SKILL.md
catalog/Platform/Official-DotNet-Upgrade/skills/dotnet-aot-compat/SKILL.md
catalog/Testing/Official-DotNet-Test/skills/code-testing-extensions/SKILL.md
catalog/Testing/Official-DotNet-Test/skills/filter-syntax/SKILL.md
catalog/Testing/Official-DotNet-Test/skills/find-untested-sources/SKILL.md
catalog/Testing/Official-DotNet-Test/skills/platform-detection/SKILL.md
catalog/Testing/Official-DotNet-Test/skills/scaffold-dotnet-test-project/SKILL.md
catalog/Testing/Official-DotNet-Test/skills/test-gap-analysis/SKILL.md
catalog/Testing/Official-DotNet-Test/skills/testability-obstacle/SKILL.md
catalog/Testing/Playwright/skills/playwright-visual-testing/SKILL.md
catalog/Testing/xUnit/skills/xunit/SKILL.md
catalog/Tools/Code-Analysis/skills/code-analysis/SKILL.md
catalog/Tools/HTMLHint/skills/htmlhint/SKILL.md
catalog/Tools/Official-DotNet-Diagnostics/skills/analyzing-dotnet-performance/SKILL.md
catalog/Tools/Official-DotNet-Diagnostics/skills/clr-activation-debugging/SKILL.md
catalog/Tools/Official-DotNet-Diagnostics/skills/dotnet-trace-collect/SKILL.md
catalog/Tools/Official-DotNet-Diagnostics/skills/dump-collect/SKILL.md
catalog/Tools/Official-DotNet-MSBuild/skills/binlog-failure-analysis/SKILL.md
catalog/Tools/Official-DotNet-MSBuild/skills/copy-to-output-directory/SKILL.md
catalog/Tools/Official-DotNet-MSBuild/skills/msbuild-server/SKILL.md
catalog/Tools/Official-DotNet-MSBuild/skills/resolve-project-references/SKILL.md
catalog/Tools/ReportGenerator/skills/reportgenerator/SKILL.md
catalog/Tools/ReSharper-CLT/skills/resharper-clt/SKILL.md
catalog/Tools/Roslynator/skills/roslynator/SKILL.md
catalog/Tools/Stylelint/skills/stylelint/SKILL.md
external-sources/upstreams/webgpu-claude-skill/skills/webgpu-threejs-tsl/SKILL.md
catalog/Frameworks/Aspire/skills/aspire/SKILL.md
catalog/Frameworks/Azure-Functions/skills/azure-functions/SKILL.md
catalog/Frameworks/Blazor/skills/blazor/SKILL.md
catalog/Frameworks/Entity-Framework-6/skills/entity-framework6/SKILL.md
catalog/Frameworks/Entity-Framework-Core/skills/entity-framework-core/SKILL.md
catalog/Frameworks/MAUI/skills/maui/SKILL.md

Metadata

Files
0
Version
0559476
Hash
fd83447a
Indexed
2026-07-25 05:21

inicio - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-08-20 06:46
浙ICP备14020137号-1 $mapa de visitantes$