ASP.NET Core Interview Question #100

What are best practices for designing the ASP.NET Core middleware pipeline?

Middleware & Request Pipeline Mid-Level Intermediate

Quick Interview Answer

Keep the pipeline intentional and easy to read. Place centralized exception handling early, serve static files before expensive application processing when appropriate, establish routing before middleware that relies on endpoint metadata, and run authentication before authorization.

Detailed Explanation

Keep the pipeline intentional and easy to read. Place centralized exception handling early, serve static files before expensive application processing when appropriate, establish routing before middleware that relies on endpoint metadata, and run authentication before authorization.

Middleware should focus on HTTP cross-cutting concerns rather than business logic. Avoid unnecessary work on every request, avoid blocking synchronous operations, respect cancellation where relevant, and do not modify a response after it has started.

Custom middleware should either clearly call the next component or intentionally short-circuit. Review pipeline order whenever authentication, CORS, caching, endpoints, proxies, or exception handling are changed.

Code Example

var app = builder.Build();

app.UseExceptionHandler("/Home/Error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseCors("Frontend");
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapRazorPages();

app.Run();