Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 52 ยท Practice and Review

ASP.NET Core Interview Questions

Forty ASP.NET Core interview questions with concise answers: pipeline, middleware, routing, dependency injection, auth, caching, performance and deployment.

ASP.NET Core interviews rarely ask you to recite API names. They ask you to explain why the framework works the way it does: why order matters in the pipeline, why a scoped service must not live inside a singleton, why a 401 is not a 403. This page collects forty questions in those areas, each with an answer short enough to say out loud, and a link to the lesson that teaches the topic in depth.

How to use it: cover the answer, answer aloud in two or three sentences, then compare. A strong answer states the rule, gives the reason, and names one pitfall. The questions are grouped by theme and roughly ordered from fundamentals to more advanced. Code snippets are read-only illustrations; the linked lessons have runnable versions.

Interviewers love follow-ups such as "what would break if you swapped those two lines?" Practice answering with a concrete consequence, not just a definition.

Part 1: fundamentals and hosting

1. What is ASP.NET Core? A cross-platform, open-source framework for building web apps and APIs on modern .NET. It includes the Kestrel web server, the request pipeline, routing, dependency injection, configuration, logging and several app models (minimal APIs, MVC controllers, Razor Pages, Blazor, SignalR). See What Is ASP.NET Core?.

2. What is Kestrel, and do you need a reverse proxy in front of it? Kestrel is the default cross-platform web server built into ASP.NET Core. It is fast and secure enough to face the internet, but production setups usually put a reverse proxy (nginx, IIS, a cloud load balancer) in front for TLS termination, load balancing, static file offloading and extra hardening. Behind a proxy you must configure forwarded headers so the app sees the real client address and scheme. See Deployment.

3. What does WebApplication.CreateBuilder(args) set up? It creates a builder with defaults: Kestrel and IIS integration, configuration from appsettings.json, appsettings.{Environment}.json, user secrets (in Development), environment variables and command-line arguments, console and debug logging, and the DI container. See The Host and the Builder.

4. What is the difference between app.Run() and app.RunAsync() and StartAsync()? Run() starts the server and blocks the calling thread until shutdown. RunAsync() does the same but returns a task you can await. StartAsync() starts the server and returns as soon as it is listening, leaving shutdown to a separate StopAsync(); tests and tools use it. See Your First Web App.

5. Why must you register services before Build()? Build() freezes the service collection into the container. Registrations made afterwards are not part of it, and the builder will not even let you add them. Order is: configure the builder and services, build, then configure the pipeline on the app.

6. What is the difference between in-process and out-of-process hosting on IIS? In-process hosting runs your app inside the IIS worker process (w3wp.exe) using the IIS HTTP server, which avoids a network hop and is faster. Out-of-process runs Kestrel in a separate process with IIS acting as a reverse proxy. In-process is the default on IIS since ASP.NET Core 3.0.

7. What does the Web SDK change in a project? A project file with Sdk="Microsoft.NET.Sdk.Web" references the ASP.NET Core shared framework automatically, enables implicit usings for web namespaces and sets up publishing and static web asset conventions. See Anatomy of a Project.

8. What is the generic host and why does ASP.NET Core build on it? The generic host (IHost) is the shared startup and lifetime layer for any .NET app: configuration, DI, logging and hosted services. A web app is a host with a web server added as a hosted service. That is why background workers, console services and web apps share the same patterns.

Part 2: routing, binding and results

9. What is the difference between minimal APIs and controllers? Minimal APIs map a URL pattern and verb directly to a delegate and have little ceremony and low overhead. Controllers group actions in classes with attributes, filters, built-in model-binding conventions and a long-established ecosystem. Both use the same routing, middleware and DI. Minimal APIs fit small services; controllers help large teams that want conventions. See Minimal API Endpoints and Controllers and Actions.

10. How does endpoint routing work? Routing matches the request to an endpoint (a handler plus metadata) and stores the match; later middleware such as authorization can read the endpoint's metadata; finally the endpoint middleware runs the handler. With WebApplication the matching and endpoint-running middleware are added for you, but where you place other middleware relative to them still matters. See Route Templates and Constraints.

11. What are route constraints and what happens when one fails? A constraint, as in {id:int:min(1)}, restricts which values a parameter accepts. If the value fails the constraint the route does not match at all, so you usually get 404, not a validation error. For input validation that should produce a 400, validate in the handler or a filter.

12. Where can a minimal API parameter come from? By default: a route value if the name appears in the template, a registered service if the type is known to DI, a special type (HttpContext, CancellationToken, ClaimsPrincipal), the query string for simple types, and the JSON body for a complex type. Attributes such as [FromHeader], [FromQuery], [FromBody], [FromForm] and [FromServices] override the guess. See Parameter Binding.

13. What does [AsParameters] do? It lets you gather several endpoint parameters into one record or class, so a long parameter list becomes a single typed object whose properties bind individually from route, query, headers or services. It keeps handlers short and the shape reusable.

14. Results versus TypedResults? Both create IResult responses. TypedResults returns concrete types such as Ok<T> and NotFound, which are visible to the compiler and to OpenAPI generation, and makes unit tests easy (you can assert on Ok<T>.Value). Results returns the plain IResult interface. Declaring Results<Ok<Post>, NotFound> documents every outcome. See Responses, Results and Content Negotiation.

Part 3: middleware and the pipeline

15. What is middleware? A component in the request pipeline that receives the HttpContext and a next delegate. It can do work before calling next, after it returns, or skip next to end the request. The pipeline is the ordered chain of those components. See The Middleware Pipeline.

16. Why does the order of middleware matter? Each component sees the request in registration order and the response in reverse. Exception handling must come first to catch errors from everything after it; UseAuthentication must precede UseAuthorization; UseCors must run before components that might short-circuit; static files usually come before routing to skip it for assets. A wrong order often compiles and runs, but quietly misbehaves.

17. Use, Run, Map and MapWhen: what is the difference? Use adds middleware that can call next. Run adds terminal middleware that never calls next. Map branches the pipeline by path prefix. MapWhen branches by any predicate on the HttpContext. A branch does not rejoin the main pipeline.

18. How do you write custom middleware? Inline with app.Use(async (context, next) => { ...; await next(); ... }), or as a class with a constructor taking RequestDelegate next and an InvokeAsync(HttpContext context) method (extra services go in InvokeAsync parameters), or by implementing IMiddleware for per-request activation from DI. See Writing Custom Middleware.

19. What is the difference between middleware and filters? Middleware runs for every request in the pipeline and knows nothing about the chosen endpoint's parameters or result. Filters (MVC action filters, minimal API endpoint filters) run only around specific endpoints, after routing, and can see bound arguments and the result. Use middleware for cross-cutting HTTP concerns (logging, compression, security headers) and filters for per-endpoint logic (validation, result shaping). See Endpoint Filters.

20. What are the rules about changing a response? Once the response has started (headers sent), you cannot change the status code or headers. context.Response.HasStarted tells you. Middleware that must add headers does so before calling next, or uses Response.OnStarting to run a callback right before the headers go out. See HttpContext, Request and Response.

C#
app.Use(async (context, next) =>
{
    context.Response.OnStarting(() =>
    {
        context.Response.Headers["X-App"] = "demo";
        return Task.CompletedTask;
    });
    await next();
});

Part 4: dependency injection, configuration and logging

21. What are the three service lifetimes? Transient: a new instance every time it is requested. Scoped: one instance per scope, which in a web app means per request. Singleton: one instance for the application's lifetime. See Dependency Injection in ASP.NET Core.

22. What is a captive dependency? A longer-lived service holding a shorter-lived one, for example a singleton that injects a scoped DbContext. The scoped instance is then kept alive for the app's life, shared across requests and possibly across threads. The framework detects this in Development with scope validation (ValidateScopes); fix it by injecting IServiceScopeFactory and creating a scope for each unit of work.

23. Why is HttpContext not safe to store in a singleton? A HttpContext belongs to one request and is reused afterwards, so keeping a reference leads to bugs and cross-request leaks. It is also not thread-safe. If a singleton needs request data, inject IHttpContextAccessor and read it on demand, and prefer passing the values you need as parameters.

24. What are keyed services? Since .NET 8 you can register several implementations of one interface under different keys (AddKeyedSingleton<ICache>("fast", ...)) and request one with [FromKeyedServices("fast")]. They replace hand-written factories for simple "pick by name" cases.

25. What is the configuration precedence? Later providers override earlier ones. The default order is appsettings.json, appsettings.{Environment}.json, user secrets (Development only), environment variables, then command-line arguments. A value on the command line wins over everything. See Configuration and the Options Pattern.

26. IOptions, IOptionsSnapshot and IOptionsMonitor? IOptions<T> is a singleton that reads values once, so it never sees changes. IOptionsSnapshot<T> is scoped, so each request sees fresh values after a file change. IOptionsMonitor<T> is a singleton that always returns current values and raises a change notification, so it is the right choice inside singletons. Use ValidateOnStart() so bad configuration fails at startup, not at 3 a.m.

27. How does ILogger work, and what is structured logging? ILogger<T> writes events with a category (the type name) and a level (Trace to Critical) to every registered provider. Structured logging keeps the template and the values separate: logger.LogInformation("Order {OrderId} shipped", id) stores OrderId as a field a log system can search, instead of baking it into a string. Never build the message with string interpolation. See Logging and Diagnostics.

Part 5: authentication, authorization and security

28. Authentication versus authorization? Authentication establishes who the caller is (it produces a ClaimsPrincipal). Authorization decides what that caller may do. They are separate middleware, and authentication must run first. See Authentication Concepts.

29. What is the difference between 401 and 403? 401 Unauthorized means the caller is not authenticated (no credentials or invalid ones); the server challenges. 403 Forbidden means the caller is authenticated but not allowed; the server forbids. Returning the wrong one misleads clients, which retry credentials on 401 but not on 403.

30. What are claims, identities and principals? A claim is a statement about a subject (name = Ann, role = admin). A ClaimsIdentity is a set of claims from one authentication source. A ClaimsPrincipal can hold several identities and is what HttpContext.User exposes.

31. How do roles, policies and requirements relate? A role check is the simplest policy (RequireRole("admin")). A policy is a named set of requirements, each checked by one or more handlers. A requirement is satisfied if any of its handlers succeeds and none calls Fail(). Use policies when rules involve claims, age, tenant or custom logic. See Authorization: Roles, Policies and Handlers.

32. What is resource-based authorization? Authorization that depends on the object being accessed, such as "only the owner may edit this note". The handler needs the loaded resource, so you load it first and call IAuthorizationService.AuthorizeAsync(user, resource, requirement) instead of using an attribute.

33. How does JWT bearer authentication validate a token? It checks the signature against the configured key, then the issuer, audience and lifetime (exp, nbf), according to TokenValidationParameters. If all checks pass, the claims in the token become the principal. The server needs no session store, but a token cannot easily be revoked before it expires, so keep access tokens short-lived. See Cookie and JWT Bearer Authentication.

34. Which attacks should every web developer be able to explain, and how does ASP.NET Core help? Cross-site scripting (Razor encodes output by default), cross-site request forgery (antiforgery tokens for cookie-authenticated forms), SQL injection (parameterized queries, EF Core), open redirects (LocalRedirect, Url.IsLocalUrl), and transport attacks (HTTPS redirection and HSTS). Bearer-token APIs do not suffer CSRF because browsers do not attach the token automatically. See Web Security Essentials.

Part 6: data, performance, testing and deployment

35. How do you avoid blocking threads in ASP.NET Core? Use async/await all the way down, pass a CancellationToken, and never call .Result, .Wait() or Thread.Sleep in a request path. Blocking holds a thread-pool thread while waiting; under load the pool starves and latency explodes even though the CPU is idle. See Performance Tuning.

36. Why use IHttpClientFactory instead of new HttpClient() per call? Creating a client per request can exhaust sockets (connections linger after disposal), while a single static client never refreshes DNS. The factory pools and recycles the underlying handlers, supports named and typed clients, and is the place to attach delegating handlers for retries and logging. See Calling Other Services.

37. Response caching versus output caching? Response caching follows HTTP caching headers and mostly helps proxies and browsers. Output caching stores finished responses on the server under rules you control (policies, vary-by keys, tags, eviction), regardless of what the client sent. See Caching.

38. What is built-in rate limiting and when would you use it? Middleware (AddRateLimiter, UseRateLimiter) with fixed window, sliding window, token bucket and concurrency limiters. Apply it to protect expensive or abusable endpoints and return 429 Too Many Requests. Partition by user or IP so one caller cannot exhaust the budget. See Rate Limiting, Health Checks and Resilience of the App.

39. How do you test an ASP.NET Core app? Unit-test logic that is separated from HTTP (services, handlers, validators), and integration-test the whole pipeline with WebApplicationFactory<TEntryPoint>, which hosts the app in memory and gives you an HttpClient. Replace external dependencies by overriding registrations. See Testing ASP.NET Core Apps.

40. What are liveness and readiness health checks? A liveness check answers "is the process alive?" and a failure means restart it. A readiness check answers "can it serve traffic now?" (database reachable, caches warm) and a failure means stop routing requests to it without restarting. Mixing the two causes restart storms when a shared dependency blips. See Rate Limiting, Health Checks and Resilience of the App.

Bonus: questions to ask back

An interview goes both ways. Good questions to ask a team: how do they handle configuration and secrets across environments, what do their health checks measure, how do they test the pipeline, and how do they deploy and roll back. Listening to those answers tells you more about the codebase than the job description does.

flowchart LR
    A["Request"] --> B["Exception handling"]
    B --> C["HTTPS and static files"]
    C --> D["Routing"]
    D --> E["CORS"]
    E --> F["Authentication"]
    F --> G["Authorization"]
    G --> H["Endpoint"]

A typical middleware order that answers most "why does the order matter?" follow-ups.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A singleton service takes a scoped service in its constructor. What is this bug called, and what is the fix?

    The singleton keeps the scoped instance alive for the app's life, so it stops being per-request. Creating a scope from IServiceScopeFactory gives each unit of work a correct instance.
  2. 2. An authenticated user without the required role calls an endpoint. Which response is correct?

    The user is known but not permitted. 401 is for missing or invalid credentials.
  3. 3. Which type should a singleton use when it needs to see configuration changes at run time?

    IOptionsMonitor<T> is a singleton that always returns current values and can notify on change. IOptionsSnapshot is scoped, so a singleton cannot use it, and IOptions never updates.
  4. 4. Why should exception-handling middleware be registered first?

    Middleware wraps everything after it. To catch exceptions from the rest of the pipeline, the handler must sit outside (before) it.
  5. 5. Which approach best avoids socket exhaustion when calling other services over HTTP?

    The factory pools and recycles handlers, which avoids both lingering sockets and stale DNS.

Summary

  • Be ready to explain the pipeline: ordered middleware, next, short-circuiting, and why order changes behavior.
  • Know the three DI lifetimes, the captive dependency trap, and the three options interfaces.
  • Distinguish authentication from authorization, and 401 from 403.
  • Know routing basics: constraints that fail give 404, binding sources, Results versus TypedResults.
  • Be able to name the performance basics: async everywhere, IHttpClientFactory, caching, rate limiting.
  • Describe testing with WebApplicationFactory and health checks as liveness versus readiness.

Next: ASP.NET Core Cheat Sheet