
Loading
A comprehensive guide to common .NET Core interview questions and answers.
Rich answers, explanations, tips, and code blocks in one reading flow.
The ASP.NET Core request pipeline consists of a sequence of bidirectional delegates (called middleware) called one after another. It handles HTTP requests and returns responses. It operates using a "Russian doll" model, where each middleware can perform logic both before and after the next component in the pipeline executes.
A middleware component can also choose to short-circuit the pipeline by not calling the next middleware, which is useful for tasks like authorization, caching, or rate limiting.
Custom middleware is typically implemented as a standard class with a specific pattern, and registered using an extension method. Here is how to construct a standard, class-based middleware that logs execution time:
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Threading.Tasks;
public class ResponseTimeMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ResponseTimeMiddleware> _logger;
// The next middleware in the pipeline is injected via the constructor
public ResponseTimeMiddleware(RequestDelegate next, ILogger<ResponseTimeMiddleware> logger)
{
_next = next;
_logger = logger;
}
// InvokeAsync must accept HttpContext as the first parameter
public async Task InvokeAsync(HttpContext context)
{
var watch = Stopwatch.StartNew();
// 1. Logic before the next middleware
_logger.LogInformation("Processing request: {Path}", context.Request.Path);
// 2. Call the next middleware in the pipeline
await _next(context);
// 3. Logic after the next middleware
watch.Stop();
_logger.LogInformation("Request processed in {Elapsed}ms", watch.ElapsedMilliseconds);
}
}To keep the configuration clean, expose the middleware via an extension method on IApplicationBuilder:
using Microsoft.AspNetCore.Builder;
public static class ResponseTimeMiddlewareExtensions
{
public static IApplicationBuilder UseResponseTime(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ResponseTimeMiddleware>();
}
}Then, register it in your Program.cs file:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Register custom middleware in the pipeline
app.UseResponseTime();
app.MapGet("/", () => "Hello World!");
app.Run();At its core, the pipeline is a chain of RequestDelegate instances (a delegate representing a function that takes an HttpContext and returns a Task). When you call await _next(context), you are invoking the next RequestDelegate in the chain.
Standard class-based middleware is instantiated as a Singleton when the application starts. Because of this, you must follow strict guidelines regarding dependency injection:
InvokeAsync method, like so: public async Task InvokeAsync(HttpContext context, IMyScopedService scopedService). ASP.NET Core resolves these dependencies per-request when invoking the method.If you prefer strongly-typed middleware resolved via the dependency injection container, you can implement the IMiddleware interface. Unlike standard middleware, factory-based middleware is registered with a lifetime (typically Scoped or Transient), allowing you to safely inject scoped dependencies directly into its constructor.
UseRouting() must run before UseAuthorization(), and error handling middleware should be placed at the very beginning of the pipeline to catch exceptions from downstream components.401 Unauthorized or serving static files without hitting the MVC/routing middleware).Continue from topic preparation into matching openings.
Capgemini
Mumbai, MH, IN
Focus the question set by company or jump to another topic.