ASP.NET Core Interview Question #8

What is middleware in ASP.NET Core?

ASP.NET Core Fundamentals Junior Beginner

Quick Interview Answer

Middleware is software assembled into the HTTP pipeline to handle requests and responses. Each middleware component typically receives an HttpContext and a RequestDelegate representing the next component in the pipeline.

Detailed Explanation

Middleware is software assembled into the HTTP pipeline to handle requests and responses. Each middleware component typically receives an HttpContext and a RequestDelegate representing the next component in the pipeline.

Common built-in middleware handles exception processing, HTTPS redirection, static files, routing, authentication, authorization, sessions, CORS, and response compression. Custom middleware can be created for application-specific cross-cutting concerns.

Code Example

app.Use(async (context, next) =>
{
    var started = DateTime.UtcNow;
    await next();
    var elapsed = DateTime.UtcNow - started;
    Console.WriteLine($"{context.Request.Path}: {elapsed.TotalMilliseconds} ms");
});