middleware-patterns
БесплатноБез исполняемых скриптовНе проверенCustom middleware patterns for ASP.NET Core applications. Covers request/response pipeline, middleware ordering, conditional middleware, IMiddleware factory…
от wshaddix★ 94 звезды на GitHubОб этом скилле
ASP.NET Core Middleware Patterns
Rationale
Middleware is the backbone of ASP.NET Core request processing. Properly designed middleware enables cross-cutting concerns like logging, authentication, and caching. Understanding the pipeline order and middleware patterns is critical for building robust applications.
Pipeline Ordering
Middleware executes in the order it is registered. The order is critical -- placing middleware in the wrong position causes subtle bugs.
Recommended Order
var app = builder.Build();
// 1. Exception handling (outermost -- catches everything below)
app.UseExceptionHandler("/error");
// 2. HSTS (before any response is sent)
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
}
// 3. HTTPS redirection
app.UseHttpsRedirection();
// 4. Static files (short-circuits for static content before routing)
app.UseStaticFiles();
// 5. Routing (matches endpoints but does not execute them yet)
app.UseRouting();
// 6. CORS (must be after routing, before auth)
app.UseCors();
// 7. Authentication (identifies the user)
app.UseAuthentication();
// 8. Authorization (checks permissions against the matched endpoint)
app.UseAuthorization();
// 9. Custom middleware (runs after auth, before endpoint execution)
app.UseRequestLogging();
// 10. Endpoint execution (terminal -- executes the matched endpoint)
app.MapControllers();
app.MapRazorPages();
Why Order Matters
| Mistake | Consequence |
|---|---|
UseAuthorization() before UseRouting() |
Authorization has no endpoint metadata -- all requests pass |
UseCors() after UseAuthorization() |
Preflight requests fail because they lack auth tokens |
UseExceptionHandler() after custom middleware |
Exceptions in custom middleware are unhandled |
UseStaticFiles() after UseAuthorization() |
Static files require authentication unnecessarily |
Pattern 1: Convention-Based Middleware
Convention-based middleware uses a constructor with RequestDelegate and an InvokeAsync method.
public sealed 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 stopwatch = Stopwatch.StartNew();
try
{
await _next(context);
}
finally
{
stopwatch.Stop();
_logger.LogInformation(
"Request {Method} {Path} completed in {ElapsedMs}ms with status {StatusCode}",
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds,
context.Response.StatusCode);
}
}
}
public static class RequestTimingMiddlewareExtensions
{
public static IApplicationBuilder UseRequestTiming(this IApplicationBuilder app)
=> app.UseMiddleware<RequestTimingMiddleware>();
}
// Usage in Program.cs
app.UseRequestTiming();
Pattern 2: Factory-Based (IMiddleware)
For middleware that requires scoped services, implement IMiddleware. This uses DI to create middleware instances per-request:
public sealed class TenantMiddleware : IMiddleware
{
private readonly TenantDbContext _db;
public TenantMiddleware(TenantDbContext db)
{
_db = db;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var tenantId = context.Request.Headers["X-Tenant-Id"].FirstOrDefault();
if (tenantId is not null)
{
var tenant = await _db.Tenants.FindAsync(tenantId);
context.Items["Tenant"] = tenant;
}
await next(context);
}
}
// IMiddleware requires explicit DI registration
builder.Services.AddScoped<TenantMiddleware>();
app.UseMiddleware<TenantMiddleware>();
Convention-Based vs IMiddleware
| Aspect | Convention-based | IMiddleware |
|---|---|---|
| Lifetime | Singleton (created once) | Per-request (from DI) |
| Scoped services | Via InvokeAsync parameters only |
Via constructor injection |
| Registration | UseMiddleware<T>() only |
Requires services.Add*<T>() + UseMiddleware<T>() |
| Performance | Slightly faster | Resolved from DI each request |
Pattern 3: Inline Middleware
For simple, one-off logic:
app.Use -- Pass-Through
app.Use(async (context, next) =>
{
context.Response.Headers["X-Request-Id"] = context.TraceIdentifier;
await next(context);
});
app.Run -- Terminal
app.Run(async context =>
{
await context.Response.WriteAsync("Fallback response");
});
app.Map -- Branch by Path
app.Map("/api/diagnostics", diagnosticApp =>
{
diagnosticApp.Run(asy
Установить middleware-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл middleware-patterns?
Custom middleware patterns for ASP.NET Core applications. Covers request/response pipeline, middleware ordering, conditional middleware, IMiddleware factory pattern, IExceptionHandler (.NET 8+), and reusable middleware components. Use when creating custom middleware in ASP.NET Core applications, understanding middleware pipeline ordering, or implementing cross-cutting concerns like logging, authentication, and caching.
Как установить скилл middleware-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл middleware-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
ci-review
The scan that the plugin's GitHub Action runs.
от Anthropicazure-static-web-apps
Helps create, configure, and deploy Azure Static Web Apps using the SWA CLI. Use when deploying static sites to Azure, setting up SWA local development…
от GitHubai-ready
Make any repo AI-ready — analyzes your codebase and generates AGENTS.md, copilot-instructions.md, CI workflows, issue templates, and more. Mines your PR…
от GitHubaws-cdk-python-setup
Setup and initialization guide for developing AWS CDK (Cloud Development Kit) applications in Python. This skill enables users to configure environment…
от GitHub