What is Middleware?
A component in ASP.NET Core that processes HTTP requests and responses in a pipeline.
Runs in sequence → Can handle/modify request → Call next → Return response
Middleware Pipeline Flow
Request → [Exception Handler]
→ [Routing]
→ [Authentication]
→ [Authorization]
→ [Custom Middleware]
→ [Endpoints]
Response ←──────────────────────────
Registering Middleware
app.UseMiddleware<CustomMiddleware>();
app.Use(async (context, next) =>
{
// before next middleware
await next();
// after next middleware
});
Built-In Middleware (Order Matters)
| Category | Examples |
|---|---|
| Error Handling | UseExceptionHandler(), UseDeveloperExceptionPage() |
| Routing | UseRouting() |
| Security | UseAuthentication(), UseAuthorization(), UseCors() |
| Performance | UseResponseCompression() |
| Session | UseSession() |
| Static Files | UseStaticFiles() |
| Endpoint Mapping | UseEndpoints() |
Middleware Rules
1. Must call await next() to continue
2. Order is very important
3. Do not run time-heavy logic
4. Avoid database calls unless required
Custom Middleware Example
public class RequestLogMiddleware
{
private readonly RequestDelegate _next;
public RequestLogMiddleware(RequestDelegate next) => _next = next;
public async Task Invoke(HttpContext context)
{
Console.WriteLine("Request: " + context.Request.Path);
await _next(context);
}
}
Register
app.UseMiddleware<RequestLogMiddleware>();
Dependency Injection (DI) Cheat Sheet
What is DI?
Design pattern where dependencies are injected instead of being hard-coded.
.NET Core has a built-in DI container
DI Service Lifetimes
| Lifetime | Scope | Best For |
|---|---|---|
| Singleton | App lifetime | Config, Cache, Logging |
| Scoped | Per request | DbContext, business services |
| Transient | New instance | Lightweight services, helpers |

Join the conversation! Your thoughts help the community grow.