wasAsked.

Explain Middleware

HCA Healthcare · Role not specified · technical

Published

Year not specified · .NET

Community answers

Posted by wasAsked editorial collection

Middleware is software assembled into a pipeline that handles every HTTP request and response in ASP.NET Core. Each component can inspect or modify the request, decide whether to call the next component, and then inspect or modify the response on the way back. Pipeline order matters. A typical Program.cs: app.UseExceptionHandler("/error"); app.UseHsts(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); Authentication must run before authorization, and the exception handler is first so it can catch errors from everything after it. Writing custom middleware: public sealed class RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> log) { public async Task InvokeAsync(HttpContext context) { var started = Stopwatch.GetTimestamp(); await next(context); // call the rest of the pipeline log.LogInformation("{Path} took {Ms} ms", context.Request.Path, Stopwatch.GetElapsedTime(started).TotalMilliseconds); } } app.UseMiddleware<RequestTimingMiddleware>(); Useful facts: - app.Use adds middleware that can call next; app.Run adds terminal middleware that ends the pipeline; app.Map and MapWhen branch the pipeline by path or condition. - Short-circuiting: middleware can write a response and not call next (for example returning 401 or serving a cached response). - Conventional middleware classes are created once (singleton-like), so inject scoped services as InvokeAsync parameters, not in the constructor. Factory-based middleware (IMiddleware) is resolved per request. - Do not modify headers after the response has started; check context.Response.HasStarted. Common uses: logging, correlation IDs, exception handling, security headers, authentication, rate limiting, compression and caching. Middleware differs from MVC filters: middleware sees every request, while filters run only inside the MVC or endpoint pipeline and have access to action context such as model state.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics