-->

Sep 1, 2026

DotNet Interview Question

Topics covered: ASP.NET Core Pipeline & Middleware, Dependency Injection, Hosting & Kestrel, Filters & Endpoints, CLR & GC Generations, Span<T> & Low-Allocation, IDisposable, Task vs ValueTask, ThreadPool Mechanics, Channels & Queues, EF Core Optimization & Tracking, Resilience (Polly), OAuth2/JWT Security, and Production Diagnostics.

ASP.NET Core Pipeline, Middleware & Filters

Answer:
The request pipeline is composed of a bidirectional chain of RequestDelegate instances structured like Russian nesting dolls. Each middleware receives the HttpContext, executes pre-processing logic, awaits next(context) to invoke the downstream component, and then executes post-processing logic on the return path.
app.Use(async (context, next) => {
          // 1. Inbound processing (before endpoints)
          await next(context);
          // 2. Outbound processing (after response generation)
      });
Interview Tip: Mention that the pipeline order is strictly sequential. Misordering middleware (e.g., placing UseAuthorization before UseAuthentication) is one of the most common configuration bugs.
Answer:
Short-circuiting occurs when a middleware intentionally terminates request processing by returning without calling await next(context). Common production examples include:
  • Static File Middleware: Returns the file directly from disk and avoids invoking routing/controllers.
  • Authentication/Authorization Middleware: Immediately sets a 401 Unauthorized or 403 Forbidden status code if validation fails.
  • Rate Limiting / CORS Preflight: Returns an immediate 429 Too Many Requests or 204 No Content for OPTIONS requests.
Answer:
* Middleware: Operates at the transport/protocol level globally across all incoming HTTP requests before routing resolves. Use for CORS, TLS termination headers, gzip compression, and global error handling.
* Action Filters: Run inside the MVC controller pipeline after model binding and routing. They have full access to ActionExecutingContext, ModelState, and controller instances. Use for controller-specific parameter validation.
* Endpoint Filters (.NET 7+): Designed for Minimal APIs and mapped endpoints. They offer lightweight cross-cutting validation and response mapping without the performance overhead of the MVC filter pipeline.
Answer:
* app.Use(): Connects a middleware delegate to the pipeline and allows delegating execution to the next handler via next.Invoke().
* app.Run(): Terminal middleware that terminates the pipeline and never invokes a downstream delegate.
* app.Map() / app.MapWhen(): Branches the pipeline based on URL prefix matching or conditional predicate evaluation.
Answer:
* Conventional Middleware: Does not implement an interface. It requires a constructor taking RequestDelegate and an InvokeAsync(HttpContext, ...) method. It is registered as a Singleton at startup; method-injected parameters are resolved per request.
* Factory-Based Middleware (IMiddleware): Implements IMiddleware, is activated per-request via IMiddlewareFactory, and is registered in the DI container as Scoped or Transient. It allows direct constructor injection of scoped services (e.g., DbContext) without captive dependency risks.
Answer:
Once Kestrel begins streaming the response body back to the client, the HTTP status code and response headers are frozen and flushed over the TCP connection (context.Response.HasStarted == true). Attempting to modify status codes or headers downstream will throw an InvalidOperationException.
Interview Tip: Use context.Response.OnStarting() callbacks if a middleware needs to append headers right before they are flushed to the socket.
Answer:
In .NET 8+, use the IExceptionHandler interface combined with app.UseExceptionHandler(). It avoids custom try-catch middleware and integrates with standard ProblemDetails (RFC 7807):
public class GlobalExceptionHandler : IExceptionHandler
      {
          public async ValueTask<bool> TryHandleAsync(
              HttpContext context, Exception ex, CancellationToken ct)
          {
              context.Response.StatusCode = StatusCodes.Status500InternalServerError;
              await context.Response.WriteAsJsonAsync(new ProblemDetails {
                  Title = "Server Error",
                  Detail = ex.Message,
                  Status = 500
              }, ct);
              return true; // Handled
          }
      }
Answer:
Filters run in the following sequence:
  1. Authorization Filters: Evaluates identity, roles, and policies.
  2. Resource Filters: Executes before model binding (used for response caching / performance profiling).
  3. Action Filters: Runs immediately before and after the action method execution.
  4. Exception Filters: Handles unhandled exceptions thrown during action execution.
  5. Result Filters: Runs before and after the action result (e.g., view rendering or JSON serialization) is produced.
Answer:
* UseRouting(): Matches the incoming HTTP request URL and verb to an Endpoint object and stores the selection in HttpContext.GetEndpoint().
* UseEndpoints(): Actually invokes the selected endpoint delegate or controller action.

Placing middleware between UseRouting() and UseEndpoints() (e.g., UseAuthentication, UseAuthorization, UseCors) allows that middleware to inspect endpoint metadata (such as [Authorize] or [EnableCors]) before the endpoint runs.
Answer:
Endpoint filters implement IEndpointFilter and receive an EndpointFilterInvocationContext and an EndpointFilterDelegate. They can intercept arguments, run FluentValidation, and mutate return values:
app.MapPost("/orders", (Order order) => Results.Ok(order))
         .AddEndpointFilter(async (context, next) => {
             var order = context.GetArgument<Order>(0);
             if (order.Amount <= 0) 
                 return Results.BadRequest("Amount must be positive.");
             return await next(context);
         });
Answer:
By default, HttpRequest.Body is a forward-only, non-seekable network stream. To read it in custom logging or auditing middleware without breaking downstream model binding, call context.Request.EnableBuffering():
context.Request.EnableBuffering();

      using (var reader = new StreamReader(context.Request.Body, leaveOpen: true))
      {
          var body = await reader.ReadToEndAsync();
          context.Request.Body.Position = 0; // Rewind for downstream model binding
      }
      await next(context);
Answer:
* Response Compression: Intercepts outbound streams and compresses payloads (Gzip, Brotli) based on the client's Accept-Encoding request header.
* Request Decompression (.NET 7+): Inspects the incoming Content-Encoding header and wraps the request stream in a decompression stream (e.g., GZipStream) before model binding reads it.
Answer:
IFeatureCollection is a low-overhead, decoupled mechanism for the server host (Kestrel/IIS) and middleware to expose optional protocol features to downstream consumers. Examples include IHttpConnectionFeature (remote IP/ports), IHttpRequestLifetimeFeature (abort signals), and ITlsConnectionFeature (client SSL certificates).
Answer:
Conventional middleware instances are created once at application startup as Singletons. If you inject a Scoped dependency (such as EF Core's DbContext) into the middleware's constructor, it becomes captured as a single instance for the entire application life cycle, causing cross-request data leaks and concurrency exceptions.

Fix: Inject the scoped dependency directly as a parameter in the InvokeAsync(HttpContext context, MyScopedService scoped) method.
Answer:
ASP.NET Core provides built-in rate-limiting middleware (app.UseRateLimiter()) powered by System.Threading.RateLimiting. Supported partitioner algorithms include:
  • Fixed Window: Limits requests within static time intervals (e.g., 100 req/min).
  • Sliding Window: Divides windows into segments to prevent request burst spikes at window boundaries.
  • Token Bucket: Refills tokens at a constant rate, allowing controlled bursts when tokens accumulate.
  • Concurrency Limiter: Enforces a strict maximum number of concurrent in-flight requests.
Answer:
* Response Caching: Purely HTTP cache-control header driven. Relies on client/proxy cooperation, does not support server-side cache eviction, and will not cache authenticated requests.
* Output Caching: Full server-side caching engine. Supports cache tags, selective programmatic cache invalidation via IOutputCacheStore.EvictByTagAsync(), cache locking to prevent cache stampedes (thundering herds), and custom storage backends like Redis.
© 2026 HelpBox.in :: All Rights Reserved

No comments:

Post a Comment