ASP.NET Core Interview Question #76

What is middleware in ASP.NET Core?

Middleware & Request Pipeline Mid-Level Intermediate

Quick Interview Answer

Middleware is software assembled into the ASP.NET Core HTTP request pipeline. Each middleware component can inspect or modify the incoming request, perform work before or after the next component, and inspect or modify the outgoing response.

Detailed Explanation

Middleware is software assembled into the ASP.NET Core HTTP request pipeline. Each middleware component can inspect or modify the incoming request, perform work before or after the next component, and inspect or modify the outgoing response.

Middleware is commonly used for exception handling, HTTPS redirection, static files, routing, authentication, authorization, CORS, logging, and custom cross-cutting behavior.

The order in which middleware is registered is important because requests flow through the pipeline in registration order and responses flow back in reverse order.

Code Example

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();