📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What is ASP.NET Core, and how does an HTTP request flow through it end to end? Walk me from the socket to the response: Kestrel, the middleware pipeline, routing, the endpoint and back.

What ASP.NET Core is and the end-to-end request path: Kestrel accepting the connection, HttpContext creation, the middleware pipeline, endpoint routing (UseRouting and endpoint execution), the endpoint delegate and the response flowing back out.

Beginner Theory Beginner aspnet-core fundamentals kestrel middleware request-pipeline routing

🎯 Key points

  • ASP.NET Core is a cross-platform, open-source web framework on .NET 10 that runs in your own process
  • Kestrel is the built-in server: it parses HTTP/1.1, HTTP/2 (multiplexed streams) and HTTP/3 (QUIC) and creates an HttpContext per request
  • Middleware is a chain of RequestDelegate components; each can act before and after calling next, or short-circuit
  • UseRouting matches the URL to an endpoint and stores it on HttpContext; middleware after it (auth, CORS) can read the endpoint's metadata
  • The endpoint (Minimal API delegate, controller action, Razor Page) runs at the end of the pipeline and writes the response
  • The response travels back out through the same middleware in reverse order, so order of registration matters
  • Services come from the DI container via HttpContext.RequestServices, with a scope per request
  • In production Kestrel needs HTTPS, request limits and forwarded headers; a proxy or cloud load balancer adds TLS offload, WAF and load balancing

⏱ 30-second answer

ASP.NET Core is Microsoft's cross-platform web framework for .NET 10: your app is a normal console process that hosts its own web server. A request arrives at Kestrel, which parses the HTTP bytes and builds an HttpContext. That context is passed through the middleware pipeline, an ordered chain of RequestDelegates registered in Program.cs. Along the way UseRouting matches the URL to an endpoint (a Minimal API handler, controller action or Razor Page), later middleware such as authentication and authorisation uses that endpoint's metadata, and finally the endpoint runs and writes the response. The response then unwinds back through the middleware in reverse. The key trade-off: the pipeline is tiny and fast because you only add what you need, but order is behaviour, so a wrongly ordered Use... call silently changes what happens.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"ASP.NET Core is the cross-platform, open-source web framework in .NET 10. The big shift from classic ASP.NET is that the app is just a console process that hosts its own web server, Kestrel, rather than being loaded by IIS. Everything is built on the Generic Host, so configuration, logging and dependency injection are set up before the first request arrives.

When a request comes in, Kestrel accepts the TCP connection, parses the HTTP/1.1, HTTP/2 or HTTP/3 frames and creates an HttpContext with the request, response, a per-request DI scope and the cancellation token for when the client goes away. That context is handed to the middleware pipeline: an ordered chain of RequestDelegates I register in Program.cs. Each middleware can do something, call next, and do something again when the response comes back, or it can short-circuit and answer itself, like the static files middleware does. UseRouting looks at the path and method and picks an endpoint; authentication, authorisation, CORS and rate limiting then read that endpoint's metadata, and the endpoint itself (a Minimal API lambda, a controller action or a Razor Page) runs at the end and writes the response, which flows back out in reverse order.

The mistake I see is people treating Program.cs as a list of features rather than a sequence. Put UseAuthorization before UseRouting and authorisation has no endpoint to check. In ASP.NET Core, the order of the pipeline is the behaviour."


The pieces and what each does

Piece Responsibility Where you see it
Kestrel Accepts connections, parses HTTP, enforces limits builder.WebHost.ConfigureKestrel
Generic Host Configuration, logging, DI, lifetime WebApplication.CreateBuilder(args)
HttpContext Request, response, user, services, RequestAborted Injected into middleware and handlers
Middleware Cross-cutting work before and after the endpoint app.Use... calls
Routing Maps method + path to an endpoint, binds route values UseRouting, MapGet, MapControllers
Endpoint Your code: Minimal API, controller action, Razor Page app.MapGet("/orders/{id}", ...)

The request path

Client ──TCP/TLS──► Kestrel ──HttpContext──► Middleware 1 ─► Middleware 2 ─► UseRouting
                                                                              β”‚ (endpoint chosen)
                                                                              β–Ό
                                                   UseAuthentication ─► UseAuthorization
                                                                              β”‚
                                                                              β–Ό
                                                                     Endpoint (your code)
Client ◄──────── Kestrel ◄─────── Middleware 1 ◄─ Middleware 2 ◄───── response written

In .NET 6+ WebApplication adds UseRouting and UseEndpoints automatically if you don't call them, which is why the minimal template has neither. Calling UseRouting explicitly is still useful when middleware must run before routing (for example UseForwardedHeaders or path rewriting).

When to use ASP.NET Core and when not

Good fit Think twice
HTTP APIs, gRPC, SignalR, server-rendered web apps Pure message-processing workers (use the Worker Service template without a web server)
Containers, Linux, Azure App Service, AKS Desktop UI
High-throughput services (Kestrel is among the fastest mainstream servers in TechEmpower benchmarks) Tiny scripts where a function trigger is simpler

Production example

In a typical order API on Azure App Service (Australia East), a request spends well under 1 ms in Kestrel and the framework middleware; the 20–80 ms you see in Application Insights is almost all database and downstream HTTP calls. Knowing the pipeline lets you read an end-to-end trace and say exactly which stage the time went to, instead of guessing.

πŸ” What the interviewer is checking

Checks that the candidate has a correct mental model of how a request moves through ASP.NET Core, not just how to scaffold an app.

Green flags

  • Names Kestrel, HttpContext, middleware, routing and the endpoint in the right order.
  • Explains that middleware runs in and then back out, and can short-circuit.
  • Knows that UseRouting selects the endpoint and authorisation reads its metadata.
  • Mentions the per-request DI scope.

Red flags

  • Thinks IIS is required or confuses ASP.NET Core with System.Web.
  • Cannot explain why middleware order matters.
  • Describes controllers as the only kind of endpoint.

πŸ“š Learn in depth

1. A process that hosts its own server

Classic ASP.NET (System.Web) was loaded into IIS's worker process and tied to Windows. ASP.NET Core flips this: your app is a Main method. WebApplication.CreateBuilder(args) builds a Generic Host that owns configuration, logging, DI and the application lifetime, and registers Kestrel as the IServer. When you call app.Run(), the host starts the server, which starts listening on the configured URLs (ASPNETCORE_URLS, launchSettings.json in development, or Kestrel:Endpoints in configuration).

2. From bytes to HttpContext

Kestrel uses System.IO.Pipelines to read socket data with few allocations. For each request it:

  1. Parses the request line and headers (HTTP/1.1) or frames (HTTP/2, HTTP/3 over QUIC).
  2. Creates an HttpContext from a pooled set of feature objects (IHttpRequestFeature, IHttpResponseFeature, ...).
  3. Creates a DI scope (HttpContext.RequestServices) so scoped services such as a DbContext live for exactly one request.
  4. Calls the application's single RequestDelegate: the whole pipeline compiled into one delegate.

3. The pipeline is one nested delegate

Each app.Use(...) wraps the next delegate:

RequestDelegate app = ctx => Mw1(ctx, () => Mw2(ctx, () => Routing(ctx, () => Endpoint(ctx))));

That is why middleware runs in registration order on the way in and reverse order on the way out, and why a middleware that never calls next short-circuits everything after it.

4. Endpoint routing is split in two

  • UseRouting (EndpointRoutingMiddleware) matches the request against all endpoints using a DFA-based matcher and calls HttpContext.SetEndpoint(...). Route values are populated here.
  • Endpoint execution (EndpointMiddleware, added implicitly at the end) invokes endpoint.RequestDelegate.

Everything between the two can call context.GetEndpoint() and read metadata such as [Authorize], RequireCors, or RequireRateLimiting. That split is the reason authorisation must come after routing.

5. The endpoint and the response

A Minimal API handler is turned into a RequestDelegate by RequestDelegateFactory (or by the Request Delegate Generator at compile time for AOT), which binds parameters and serialises the return value with System.Text.Json. Writing the first byte sends the status line and headers; after that, headers can no longer change (Response.HasStarted). Middleware that wants to modify headers on the way out must use Response.OnStarting.

6. Cost model

  • The framework overhead per request is microseconds; allocations matter more than CPU at high RPS.
  • Each extra middleware is one delegate call plus whatever it does; the expensive ones do I/O (session, response caching to a store) or buffer bodies.

Try it yourself

  1. Create dotnet new web, add three app.Use middlewares that log before and after next, and watch the order in the console.
  2. Add app.Use that writes a response without calling next and observe that MapGet never runs.
  3. Log context.GetEndpoint()?.DisplayName in middleware placed before and after app.UseRouting().
  4. Run dotnet-counters monitor -n <app> Microsoft.AspNetCore.Hosting while hitting the app with bombardier or wrk and watch requests per second and current requests.

πŸ’» Code

A minimal app that makes the request flow visible: middleware before and after routing, a short-circuit, and an endpoint.

// Program.cs (.NET 10, nullable enabled)
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(k => k.AddServerHeader = false); // don't advertise the server
var app = builder.Build();

// 1. Runs first for every request, before an endpoint is chosen
app.Use(async (context, next) =>
{
    app.Logger.LogInformation("In: {Method} {Path} over {Protocol}, endpoint={Endpoint}",
        context.Request.Method, context.Request.Path, context.Request.Protocol,
        context.GetEndpoint()?.DisplayName ?? "(none yet)");
    await next(context);
    // Runs on the way back OUT, after everything below has finished
    app.Logger.LogInformation("Out: {StatusCode}", context.Response.StatusCode);
});

// 2. Short-circuit: answers /ping itself and never calls next,
//    so routing, auth and endpoints below do not run for this path
app.Use(async (context, next) =>
{
    if (context.Request.Path == "/ping")
    {
        await context.Response.WriteAsync("pong");
        return; // short-circuit: middleware 1 still sees the response on the way out
    }
    await next(context);
});

app.UseRouting(); // 3. explicit so the next middleware can see the matched endpoint

// 4. Routing has run: auth, CORS and rate limiting read this endpoint metadata
app.Use(async (context, next) =>
{
    app.Logger.LogInformation("Matched {Endpoint}", context.GetEndpoint()?.DisplayName);
    await next(context);
});

// 5. The endpoint: last in the chain, writes the response
app.MapGet("/orders/{id:int}", (int id) => TypedResults.Ok(new Order(id, "Pending")))
   .WithName("GetOrder");

app.Run();

public sealed record Order(int Id, string Status);

Calling /orders/7 logs In β†’ Matched β†’ Out; calling /ping logs In β†’ Out only, because middleware 2 short-circuited.

⚠ Common mistakes

  • Mistake: Thinking IIS or a reverse proxy is required to run ASP.NET Core. Why it is wrong: Kestrel is a production-grade server and can face the internet directly. Instead: Decide deliberately: in production most teams still put Kestrel behind a cloud load balancer, ingress, Front Door or IIS for TLS termination, WAF rules, DDoS protection and load balancing, and then configure forwarded headers so the app sees the real scheme and client IP.
  • Mistake: Treating Program.cs as an unordered list of features. Why it is wrong: Each Use... wraps the next one, so order decides what runs and what sees the endpoint. Instead: Read the pipeline top to bottom as a sequence and follow the documented order.
  • Mistake: Putting UseAuthorization before UseRouting. Why it is wrong: No endpoint has been selected yet, so [Authorize] metadata is invisible. Instead: Routing, then authentication, then authorisation, then endpoints.
  • Mistake: Modifying response headers after calling next. Why it is wrong: Once the body starts, headers are sent and HasStarted is true; the change throws or is lost. Instead: Use context.Response.OnStarting(...) to add headers just before they are sent.
  • Mistake: Doing blocking I/O in middleware. Why it is wrong: Every request passes through it, so one .Result can starve the ThreadPool. Instead: Keep middleware async end to end.
  • Mistake: Resolving scoped services from the root provider in middleware constructors. Why it is wrong: Convention-based middleware is a singleton; a captured DbContext is shared across requests. Instead: Take scoped services as InvokeAsync parameters or use IMiddleware.
  • Mistake: Exposing Kestrel with default limits and HTTP only. Why it is wrong: No TLS, the Server: Kestrel header and unlimited header or connection counts widen the attack surface. Instead: Enable HTTPS (or terminate TLS at a trusted proxy), set AddServerHeader = false and review KestrelServerLimits.

πŸ› Senior insight: trade-offs

What separates a senior answer is seeing the pipeline as an execution model you can reason about, not a template. When a trace in Application Insights shows 400 ms, you should be able to say whether it was spent before routing (a slow custom middleware), in auth (a JWKS fetch), in the endpoint (the database) or after it (response compression of a large body). The framework gives you Microsoft.AspNetCore.Hosting and Microsoft.AspNetCore.Routing metrics and activity spans out of the box in .NET 8+, so measure before you optimise.

Option When it fits Cost When not to
Kestrel exposed directly (container behind a cloud load balancer) Containers, AKS, Container Apps You manage TLS or let the platform do it Windows servers that must share port 443 with other sites
Kestrel behind IIS (in-process) Existing Windows/IIS estates Windows-only, IIS config New greenfield services
Kestrel behind Nginx, YARP or Front Door Central TLS, WAF, path routing Extra hop, forwarded headers to configure Single small service with nothing to share

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate says middleware can stop the request or pass it on. Why: Checks whether the candidate can connect middleware to the underlying design pattern and short-circuiting.
    How to answer

    Chain of Responsibility sends a request along a chain of handlers; each one decides whether to handle it, pass it on, or both, and the sender doesn't know which one acted.

    • Classic variant: the first handler that can deal with it stops the chain, like an expense approval going team lead β†’ manager β†’ director by amount.
    • Pipeline variant: every handler can act before and after calling next. ASP.NET Core middleware (RequestDelegate next) and DelegatingHandler in HttpClient work this way.

    Short-circuiting means returning without calling next: authentication returning 401, static files serving a file, a cache hit. That's why order matters: exception handling must wrap everything, and authentication must run before authorisation.

    The trade-off is decoupling and composability against long implicit chains whose order lives far from the handlers.

  2. When: Candidate mentions Kestrel accepting the TCP connection. Why: Checks the network layer below Kestrel: DNS, TCP, TLS and HTTP.
    How to answer
    1. DNS: resolve api.example.com to an IP address (OS cache, then a resolver).
    2. IP routing: packets go from my machine through routers (and usually NAT) to that IP.
    3. TCP: connect to port 443 with a three-way handshake (SYN, SYN-ACK, ACK). One round trip.
    4. TLS: negotiate keys and verify the server's certificate for api.example.com (TLS 1.3: one more round trip).
    5. HTTP: send GET /orders/42 with headers; often a load balancer or reverse proxy terminates TLS and forwards to an app instance.
    6. Response comes back on the same connection, which HttpClient keeps alive and reuses for the next request, skipping steps 1–4.

    On a cold connection, DNS + TCP + TLS can cost more than the request itself, which is why connection reuse matters.

↩ Usually asked after

More in ASP.NET Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me