junioraspnet-core
A chain of request handlers. Each middleware can process the request, call next(), and process the response.
Requests pass through the middleware chain in registration order. Each can: handle and return a response (short-circuit), modify the request and pass it along, modify the response after next(). Order matters: Exception Handling → HSTS → Static Files → Routing → Auth → Endpoints.
var app = builder.Build();
// Порядок имеет значение!
app.UseExceptionHandler("/error");
app.UseHsts();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// Custom middleware
app.Use(async (context, next) =>
{
var sw = Stopwatch.StartNew();
await next();
logger.LogInformation("{Method} {Path} {Ms}ms",
context.Request.Method, context.Request.Path, sw.ElapsedMilliseconds);
});When yes
Logging, authentication, CORS, exception handling, rate limiting — anything cross-cutting
When no
Business logic for a specific endpoint — use endpoint handler / controller
Interview tip
Middleware order is a favorite question. UseAuthentication BEFORE UseAuthorization, both AFTER UseRouting.