| name | planforge-new-middleware |
| description | Scaffold ASP.NET Core middleware with request/response pipeline, DI support, structured logging, and proper ordering. |
| metadata | {"author":"plan-forge","source":".github/prompts/new-middleware.prompt.md"} |
description: "Scaffold ASP.NET Core middleware with request/response pipeline, DI support, structured logging, and proper ordering."
agent: "agent"
tools: [read, edit, search]
Create New Middleware
Scaffold an ASP.NET Core middleware component for the HTTP request pipeline.
Required Pattern
Convention-Based Middleware
public class {Name}Middleware(
RequestDelegate next,
ILogger<{Name}Middleware> logger)
{
public async Task InvokeAsync(HttpContext context)
{
logger.LogDebug("{Name}Middleware executing for {Path}", context.Request.Path);
try
{
await next(context);
}
finally
{
}
}
}
public static class {Name}MiddlewareExtensions
{
public static IApplicationBuilder Use{Name}(this IApplicationBuilder builder)
=> builder.UseMiddleware<{Name}Middleware>();
}
Scoped-Service Middleware (IMiddleware)
public class {Name}Middleware(ILogger<{Name}Middleware> logger) : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
await next(context);
}
}
builder.Services.AddScoped<{Name}Middleware>();
Registration Order (Program.cs)
app.UseExceptionHandler();
app.UseCorrelationId();
app.UseRequestLogging();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiting();
app.Use{Name}();
Common Middleware Types
| Type | Purpose | Example |
|---|
| Correlation ID | Attach trace ID to every request | Read/generate X-Correlation-Id header |
| Tenant Resolution | Extract tenant from token/header | Set ITenantContext.TenantId |
| Request Logging | Log method, path, status, duration | Structured log with Serilog |
| Exception Handling | Map exceptions to ProblemDetails | Global try/catch with RFC 9457 |
Rules
- Middleware handles cross-cutting concerns ONLY — no business logic
- Always call
await next(context) unless short-circuiting intentionally
- Use
finally blocks for post-processing (guarantees execution on errors)
- Add an extension method
Use{Name}() for clean Program.cs registration
- Use
IMiddleware interface when scoped DI services are needed
Reference Files