44 Most Commonly Asked ASP.NET Core Interview Questions and Answers (2026)

ASP .NET Core is the lightweight, high-performance engine powering modern web APIs and full-stack apps.
Understanding its middleware pipeline, dependency-injection model, and cross-platform hosting nuances equips you to craft faster, cleaner services, as well as the ability to show off to your interviewer.
Q1.
What is the difference between IServiceCollection and IServiceProvider in the register vs. resolve phases of the application?
They represent the two phases of DI: IServiceCollection is the registration (build-time) phase where you describe services, and IServiceProvider is the resolution (run-time) phase that hands you constructed instances.
IServiceCollection(register):A mutable list of
ServiceDescriptorentries: service type, implementation, and lifetime.Populated via
AddSingleton,AddScoped,AddTransientbefore the container is built.
IServiceProvider(resolve):The built, immutable container that actually constructs and injects instances.
Created from the collection (
BuildServiceProvider()or by the host), then used to resolve dependencies and manage scopes/lifetimes.
Order matters: once the provider is built, registrations are fixed: you register first, then resolve.
Q2.
What is the difference between inline and class-based middleware, and when is it better to encapsulate middleware in its own class?
Inline middleware is a lambda written directly in Program.cs via app.Use(...); class-based middleware lives in its own class with an Invoke/InvokeAsync method. Encapsulate in a class once the logic grows, needs dependencies, or should be reusable and testable.
Inline middleware:
Quick, declared with
app.Use(async (context, next) => {...}).Best for small, one-off concerns; clutters startup if it grows.
Class-based middleware:
A class with a constructor taking
RequestDelegate nextand anasync Task InvokeAsync(HttpContext context)method.Constructor receives singleton dependencies; per-request services are injected into
InvokeAsync.
When to encapsulate in a class:
Logic is non-trivial or has multiple branches.
It needs DI services (loggers, options, scoped services).
You want unit tests and reuse across apps via a
UseXxx()extension method.
Q3.
How does cookie-based authentication work in ASP.NET Core, and how does it differ from JWT bearer authentication?
Cookie authentication keeps session state on the client as an encrypted cookie the browser sends automatically; JWT bearer authentication uses a self-contained signed token the client sends explicitly in the Authorization header. Cookies suit server-rendered apps; JWTs suit APIs and SPAs.
How cookie auth works:
On sign-in, the server serializes the
ClaimsPrincipal, encrypts/signs it (Data Protection), and issues a cookie viaSignInAsync.The browser auto-sends the cookie each request; middleware decrypts it to rebuild the user.
Stateful feel: supports server-driven expiration, sliding renewal, and revocation by config.
How JWT bearer works:
Client obtains a signed token and sends
Authorization: Bearer <token>on each request.Server validates signature, issuer, audience, and expiry; no server-side session needed (stateless).
Claims live inside the token, so revocation before expiry is hard without extra infrastructure.
Key differences:
Transport: cookies sent automatically (CSRF risk, needs anti-forgery); bearer tokens sent manually (no CSRF, but token storage matters).
State: cookies are typically server-revocable; JWTs are self-contained and stateless.
Best fit: cookies for traditional web apps, JWT for cross-domain APIs and mobile/SPA clients.
Q4.
What is WebApplicationFactory and why is it the standard for integration testing in ASP.NET Core?
WebApplicationFactory<TEntryPoint> bootstraps your real app in memory using its actual Program startup, giving you an HttpClient that exercises the full middleware pipeline without a network socket.
What it does:
Spins up the app via a
TestServer(in-memory), so requests run through routing, filters, auth, and DI exactly as in production.Returns a configured
HttpClientthroughCreateClient().
Why it's the standard:
Tests the system as a whole rather than mocking the pipeline, catching wiring/config bugs unit tests miss.
No real ports/network, so tests are fast and reliable.
Customization:
Override services with
WithWebHostBuilder()/ConfigureTestServices()to swap a real DB for in-memory or stub external dependencies.Requires
Programto be reachable as the entry point (the implicitProgramclass in minimal hosting).
Q5.
What is ASP.NET Core Identity, and what features does it provide out of the box for user management?
ASP.NET Core Identity is a membership system that adds login, user, role, and credential management to an app, with an extensible store (EF Core by default) and APIs for password hashing, sign-in, and claims.
Core building blocks:
UserManager<TUser>andRoleManager<TRole>for CRUD on users and roles;SignInManager<TUser>for sign-in/sign-out flows.Default entities
IdentityUserandIdentityRolecan be extended with custom properties.
Out-of-the-box features:
Secure password hashing (PBKDF2) and configurable password/lockout policies.
Email/phone confirmation, password reset, two-factor authentication (2FA), and account lockout.
External logins (Google, Facebook, etc.) via OAuth providers.
Role-based and claims-based identity that integrates with the authorization system.
Storage and UI:
EF Core store via
IdentityDbContext; the store is pluggable for other databases.Scaffoldable Razor Pages UI for login/register screens, or use the API-only pieces.
Not the same as the auth pipeline: Identity manages users/credentials, while authentication middleware decides how requests are authenticated.
Don't let one question ruin your next technical interview...
Q6.
How does the Program.cs file in .NET 6/7/8+ replace the legacy Startup.cs class?
In .NET 6+ the top-level Program.cs merges what used to be split across Program.cs (host building) and Startup.cs (ConfigureServices + Configure) into a single linear file using top-level statements.
What got merged:
Startup.ConfigureServices(...)becomesbuilder.Services.Add...beforeBuild().Startup.Configure(...)becomesapp.Use.../app.Map...afterBuild().
Implementation details:
No explicit
Mainmethod or namespace boilerplate (top-level statements).DI and pipeline order are now visible in one place, in execution order.
Compatibility: the
Startuppattern still works if wired manually; it is just no longer the default template.
Q7.
What is the ASP.NET Core Middleware pipeline, and how does it differ from the old HttpModules and HttpHandlers?
The middleware pipeline is an ordered chain of components, each receiving the HttpContext and a delegate to the next component, that together process every request and response. It replaces the older, parallel HttpModules and HttpHandlers model with a single, explicit, code-configured flow.
How the pipeline works:
Each middleware can run logic, call
next, then run more logic on the way back (a nested request/response flow).Order is fully explicit, defined by registration in
Program.cs.
Old model: modules and handlers:
HttpModulessubscribed to many pipeline events; order was config-driven and harder to reason about.HttpHandlerswere the terminal endpoint that produced the response for a given request type.Tightly coupled to IIS and
System.Web.
Key differences:
Unified concept: middleware handles both module-style and handler-style roles.
Server-agnostic (Kestrel, IIS, etc.) and configured in code, not
web.config.Explicit, linear ordering instead of an event-based execution order.
Q8.
What is the IResult/Results type in Minimal APIs, and how does it compare to IActionResult in MVC?
In Minimal APIs, IResult is the return abstraction (produced by the Results and TypedResults factories) that knows how to write an HTTP response: it's the lightweight analogue of MVC's IActionResult.
Same core idea: Both let you return a status code, body, and headers without manually writing to the response.
Results vs TypedResults:
Results.Ok()returnsIResult;TypedResults.Ok()returns a concrete type, which improves testability and feeds OpenAPI metadata.Lighter pipeline:
IResultexecutes viaExecuteAsync(HttpContext)without the full MVC action-result invocation machinery.Multiple return types: Use
Results<Ok<T>, NotFound>to declare a union of possible typed results for clear, documented endpoints.
Q9.
How does the Configuration API work in ASP.NET Core, and what is the default order of precedence for configuration providers?
The Configuration API builds a single key-value store by layering multiple providers (JSON files, environment variables, command line, etc.) in order, where later providers override earlier ones for the same key. The host sets up a sensible default order you can customize.
How it works:
Each provider contributes flat key-value pairs; nested JSON uses
:as the hierarchy separator (e.g.Logging:LogLevel:Default).Access values via
IConfigurationindexers/GetSectionor bind to POCOs with the options pattern.
Default precedence (later overrides earlier):
appsettings.jsonappsettings.{Environment}.jsonUser secrets (Development only).
Environment variables.
Command-line arguments (highest).
Customizable: You can add or reorder providers; precedence is purely the order they are added to the builder.
Q10.
How does the Data Protection API work in ASP.NET Core, and what is its role in protecting cookies and anti-forgery tokens in a load-balanced environment?
The Data Protection API is ASP.NET Core's built-in cryptographic system for protecting sensitive payloads (encrypt + authenticate) without you managing keys directly. It's what secures auth cookies and antiforgery tokens, and in a load-balanced farm all servers must share its key ring so any server can decrypt what another encrypted.
What it does:
Provides
Protect()/Unprotect()over aIDataProtectorscoped by a purpose string, so tokens for one purpose can't be reused for another.Manages a rotating key ring (default 90-day lifetime) automatically.
What relies on it: Authentication cookies, antiforgery tokens, TempData, and any custom protected data.
The load-balancing problem: By default keys are stored locally (per machine, often tied to the machine), so a cookie encrypted on server A fails to decrypt on server B, causing random logouts or antiforgery errors.
The fix: shared, persisted keys:
Persist the key ring to a shared location with
PersistKeysToFileSystem(), Redis, or Azure Blob Storage.Set a common application name via
SetApplicationName()so all instances use the same isolation scope.Optionally protect the keys at rest with a certificate or Azure Key Vault.
Q11.
Explain the difference between Attribute Routing and Conventional Routing.
Both map incoming URLs to actions, but attribute routing declares routes directly on controllers/actions, while conventional routing defines URL templates centrally that apply across many controllers.
Conventional routing:
Defined once in startup with a pattern like
{controller}/{action}/{id?}.Good for MVC apps with uniform URL shapes; less repetition.
Attribute routing:
Routes declared with
[Route],[HttpGet],[HttpPost("...")]on each action.Gives precise, per-endpoint control: ideal for REST APIs with varied URLs and HTTP verbs.
Practical guidance:
Web APIs (and anything with
[ApiController]) use attribute routing; classic server-rendered MVC often uses conventional.You can mix them in one app.
Q12.
What is Content Negotiation, and how does ASP.NET Core decide whether to return JSON or XML?
Content negotiation is how a Web API picks a response format based on what the client asks for, primarily via the Accept header, choosing among the configured output formatters (JSON by default, XML if enabled).
How the choice is made:
The client sends
Accept: application/xml(or JSON); ASP.NET Core matches it against registered output formatters.If no formatter matches, it falls back to the first configured formatter (JSON).
Only triggered when the action returns an object/
ObjectResult; returning a hard-codedJsonResultbypasses negotiation.
JSON vs XML:
JSON is on by default via
System.Text.Json.XML is opt-in:
AddControllers().AddXmlSerializerFormatters().
Controlling behavior:
Set
RespectBrowserAcceptHeaderto honor browserAcceptheaders.Use
ReturnHttpNotAcceptable = trueto return406 Not Acceptableinstead of silently defaulting.The
[Produces]attribute can force a specific format on an action.
Q13.
What is the difference between HTTPS redirection and HSTS, and why are both used together?
HTTPS redirection sends users who arrive over HTTP to the HTTPS equivalent, while HSTS (HTTP Strict Transport Security) is a response header that tells the browser to never use HTTP for this site again. They're used together because redirection fixes the current request and HSTS prevents future insecure requests, closing the gap an attacker could exploit on that first plaintext hop.
HTTPS redirection:
Server-side:
UseHttpsRedirection()returns a 307/308 to thehttps://URL.Weakness: the very first HTTP request still travels in plaintext and could be intercepted (man-in-the-middle) before the redirect.
HSTS:
Client-side enforcement: the
Strict-Transport-Securityheader makes the browser auto-upgrade to HTTPS for amax-ageduration, with no HTTP request sent at all.Added via
UseHsts(); only honored over HTTPS and typically skipped in development/localhost.
Why both:
Redirection handles the user who hasn't been to your site yet; HSTS protects every visit after that, eliminating the repeated insecure first hop.
Caveat: HSTS is sticky (cached by the browser), so misconfiguring it can be hard to undo.
Q14.
Explain the difference between app.Use(), app.Run(), and app.Map().
All three add to the pipeline, but they differ in whether they call the next component and whether they branch. Use() adds middleware that can pass control onward, Run() adds a terminal middleware that never calls next, and Map() branches the pipeline based on the request path.
app.Use():Inline middleware receiving
contextandnext; callingawait next()continues the pipeline.Can run logic before and after the rest of the pipeline.
app.Run():Terminal: it has no
nextparameter and ends the pipeline by producing a response.Anything registered after it for that branch never runs.
app.Map():Branches the pipeline on a path prefix; the branch gets its own middleware chain.
Variant
MapWhen()branches on an arbitrary predicate of the request.
Q15.
Can you use Filters with Minimal APIs? If not, what is the equivalent?
You can't use MVC action filters (IActionFilter, etc.) with Minimal APIs, but the equivalent is endpoint filters via IEndpointFilter / AddEndpointFilter(), introduced in .NET 7.
Endpoint filters wrap the handler: They run before and after the endpoint, can inspect/modify arguments, short-circuit with a result, or run cross-cutting logic (validation, logging).
Applied per endpoint or per group: Call
.AddEndpointFilter<T>()on a singleMapGetor on aRouteGroupBuilderto apply to all endpoints in the group.You still have middleware: For truly global cross-cutting concerns, middleware remains available alongside endpoint filters.
Q16.
What is the difference between Authentication and Authorization in the context of ASP.NET Core?
Authentication establishes who you are; authorization decides what you're allowed to do. Authentication always comes first because authorization decisions are made about an authenticated identity.
Authentication (AuthN):
Validates credentials/tokens and builds a
ClaimsPrincipalrepresenting the user.Configured via schemes (cookies, JWT bearer) and run by
UseAuthentication().
Authorization (AuthZ):
Evaluates whether that identity may access a resource via roles, claims, or policies.
Enforced by
[Authorize]and run byUseAuthorization().
Order matters in the pipeline: Call
UseAuthentication()beforeUseAuthorization(), or the user identity won't exist when authorization runs.
Q17.
What is the difference between GetRequiredService<T>() and GetService<T>()?
Both resolve a service from the container, but they differ in what happens when the service is not registered: GetService<T>() returns null, while GetRequiredService<T>() throws an exception.
GetService<T>():Returns
nullif the type is not registered, so you must null-check before use.Use when a dependency is genuinely optional.
GetRequiredService<T>():Throws
InvalidOperationExceptionif the type is missing, failing fast at the point of the mistake.Preferred for required dependencies: clearer error than a later
NullReferenceException.
Both live on
IServiceProvider(the latter is an extension method inMicrosoft.Extensions.DependencyInjection).
Q18.
How does localization and globalization work in ASP.NET Core, and what is the role of resource files and request culture providers?
Globalization adapts formatting (dates, numbers, currency) to a culture, while localization swaps translated text; ASP.NET Core resolves a request's culture via culture providers and looks up translated strings in resource (.resx) files.
Globalization vs localization:
Globalization:
CultureInfodrives number/date formatting (theCulture).Localization: translating UI text, driven by the
UICulture.
Resource files (
.resx):Named per culture (e.g.
Messages.fr.resx,Messages.es.resx) with a default fallback.Accessed via
IStringLocalizer<T>/IViewLocalizer; missing keys fall back to the default resource.
Request culture providers:
Configured via
UseRequestLocalization()and run in order until one resolves a culture.Built-ins:
QueryStringRequestCultureProvider,CookieRequestCultureProvider,AcceptLanguageHeaderRequestCultureProvider.You declare
SupportedCulturesandSupportedUICulturesso requests are clamped to what you actually support.
Q19.
What is the JWT Bearer flow, and how does the server validate a token without calling an external identity provider on every request?
In the JWT bearer flow, an identity provider issues a signed token after login; the client sends it on each request in the Authorization: Bearer <token> header. The API validates the token locally by checking its signature and claims, so it doesn't need to call the issuer per request.
The flow:
User authenticates; the issuer returns a signed JWT (header, claims payload, signature).
Client stores it and attaches it to subsequent API calls as a bearer token.
API validates and builds a
ClaimsPrincipalfrom the token's claims.
Why no per-request call to the IdP:
JWTs are self-contained and signed, so validity is checked cryptographically.
Symmetric keys or (more commonly) the issuer's public keys are used; public keys are fetched from the OIDC discovery / JWKS endpoint and cached, not requested every time.
What the server validates: Signature, expiry (
exp), issuer (iss), and audience (aud).Trade-off: Stateless and fast, but a token can't be easily revoked before expiry, so keep lifetimes short and use refresh tokens.
Q20.
What are keyed services (introduced in .NET 8), and what problem do they solve?
Keyed services, added in .NET 8, let you register multiple implementations of the same interface under distinct keys and resolve a specific one by key. They solve the problem of needing several variants of one service without custom factories or marker interfaces.
The problem before .NET 8: Registering two
INotificationServiceimplementations meant the last one won, or you injectedIEnumerable<T>and filtered manually.How keyed services work:
Register with
AddKeyedScoped/AddKeyedSingleton/AddKeyedTransientplus a key.Resolve with the
[FromKeyedServices("key")]attribute orGetRequiredKeyedService.
When to use: Strategy-style selection (e.g. "sms" vs "email" sender, primary vs read-replica connections).
Q21.
What is Endpoint Routing, and how does it allow middleware to be aware of the selected endpoint before it is executed?
Endpoint Routing splits routing into two stages: UseRouting matches the request to an endpoint and stores it on the context, while UseEndpoints actually executes it. The gap between them lets intervening middleware inspect the chosen endpoint and its metadata before it runs.
Two-phase model:
UseRoutingdecides which endpoint matches but does not invoke it.The selected endpoint is exposed via
HttpContext.GetEndpoint().UseEndpointsruns the matched delegate at the end of the pipeline.
Why this matters:
Middleware placed between routing and endpoints can read endpoint metadata (
[Authorize], CORS policy, route values) and act on it.This is why
UseAuthorizationcan enforce an endpoint's policy: the endpoint is already known.
Q22.
How can you share data across different middleware components during a single request?
The canonical way is HttpContext.Items, a per-request dictionary that lives for the lifetime of a single request and is cleared afterward. For richer scenarios you can also use scoped DI services.
HttpContext.Items:An
IDictionary<object, object>scoped to the current request only.One middleware writes a key, a later one reads it; ideal for transient request-scoped data.
Scoped DI services:
A service registered with
AddScopedhas one instance per request, so state set in one middleware is visible to others resolving the same scope.Better when the shared data has behavior or needs typing rather than a loose dictionary entry.
Avoid: Singletons or static fields for per-request data: they are shared across all requests and cause race conditions.
Q23.
How do you short-circuit the middleware pipeline, and what is the behavior of app.Run() versus app.Use() and app.Map()?
You short-circuit the pipeline by not calling the next delegate, so the current middleware produces the final response. app.Run() is inherently terminal, while app.Use() decides at runtime whether to continue, and app.Map() creates a separate branch that handles matching requests.
Short-circuiting:
Skip
await next()and write to the response; downstream middleware and the endpoint never run.Common for auth rejection, caching hits, and rate limiting.
app.Run():Terminal middleware with no
next; always short-circuits by ending the chain.Anything registered after it (in that branch) is unreachable.
app.Use(): Non-terminal by convention: continues if it callsnext, short-circuits if it doesn't.app.Map(): Branches by path prefix; the branch runs its own middleware and typically ends in its ownRun().
Q24.
What are the differences between Razor Pages and MVC controllers, and when would you choose one over the other?
Razor Pages organize code around individual pages (a page plus its page model), while MVC separates concerns into controllers, models, and views. Both run on the same underlying framework; the difference is how you structure request handling.
Razor Pages:
A
.cshtmlpage paired with aPageModelcontaining handlers likeOnGet/OnPost.Page-centric and cohesive: best for form-driven, page-oriented UIs with simpler routing.
MVC controllers:
One controller exposes many actions returning views or data; clearer separation of concerns.
Better for complex apps, shared logic across actions, and REST APIs.
When to choose which:
Server-rendered, page-focused web app: Razor Pages reduces ceremony.
APIs or large apps with rich routing/cross-cutting logic: MVC controllers.
Q25.
What is a captive dependency, how does it happen, and why is it dangerous for application stability?
A captive dependency happens when a longer-lived service holds a reference to a shorter-lived one, effectively "capturing" it and keeping it alive beyond its intended lifetime: most commonly a Singleton depending on a Scoped service.
How it happens:
A
Singletoninjects aScoped(orTransient) service in its constructor; that instance is resolved once and reused forever.The captured instance never gets a fresh per-request lifetime as intended.
Why it is dangerous:
State bleeds across requests: a per-request object now shared by all requests can leak data or cause race conditions.
Resources like a
DbContextstay open far too long, causing stale data, connection issues, and threading bugs.
How ASP.NET Core protects you: Scope validation (on by default in Development) throws at startup if a singleton consumes a scoped service via
BuildServiceProvidervalidation.The fix: Inject
IServiceScopeFactoryinto the singleton and create a scope per unit of work to resolve the scoped service on demand.
Q26.
What is the difference between Response Caching and Output Caching, and which is client/proxy-based vs. server-side?
Response Caching sets HTTP cache headers so clients and proxies cache the response (client/proxy-based), while Output Caching (.NET 7+) stores rendered responses on the server under your control (server-side).
Response Caching:
Driven by
Cache-Control,Vary, etc.; the actual caching happens in the browser or an intermediary proxy.You don't fully control it: a client can ignore the headers, and it won't cache responses with auth or
Set-Cookie.
Output Caching:
Stores the response server-side (in memory or a distributed store), so you control eviction, expiration, and
tag-based invalidation.Works regardless of client behavior and supports cookies/auth scenarios.
Wiring: Output Caching uses
AddOutputCache()+UseOutputCache()and.CacheOutput()on endpoints.
Q27.
Explain the concept of Claims-based Authorization versus Role-based Authorization.
Both are built on claims, but role-based authorization checks a single coarse claim (the role), whereas claims-based authorization checks any claim and even its value, giving finer-grained control over access.
A claim is a key/value statement about the user:
Examples:
email,department=Finance,role=Admin.Carried in the
ClaimsPrincipalafter authentication.
Role-based:
A specialized case: it just checks for a role claim, e.g.
[Authorize(Roles = "Admin")].Simple but inflexible; roles can proliferate as needs grow.
Claims-based:
Authorizes on the presence or value of any claim, e.g.
RequireClaim("department", "Finance").Usually expressed through policies, making it more expressive and maintainable than ever-growing roles.
Q28.
Explain how CORS (Cross-Origin Resource Sharing) is configured and enforced in ASP.NET Core.
CORS is a browser security mechanism that controls whether a web page from one origin may call an API on a different origin. In ASP.NET Core you define named (or default) policies, register the CORS services, and enforce them via middleware or per-endpoint attributes; the server then emits the Access-Control-Allow-* headers the browser checks.
Why it exists: Browsers enforce the same-origin policy; CORS is how a server opts in to allowing specific cross-origin callers. It is enforced by the browser, not the server.
Configuration:
Register with
AddCors()and define policies specifying allowed origins, headers, and methods.Enable with
UseCors()(must come afterUseRouting()and before endpoints), or apply[EnableCors]/RequireCors()per endpoint.
Preflight requests: For non-simple requests the browser first sends an
OPTIONSpreflight; the middleware answers with the allowed methods/headers before the real request is sent.Common pitfalls:
AllowAnyOrigin()cannot be combined withAllowCredentials(); for credentials you must list explicit origins.CORS is not authentication: it doesn't protect the API from non-browser clients.
Q29.
How does ASP.NET Core support multiple authentication schemes, and how do you specify which scheme an endpoint uses?
ASP.NET Core lets you register several authentication schemes (each a named handler like a cookie scheme or a JWT scheme), pick a default, and override per endpoint with the [Authorize(AuthenticationSchemes = ...)] attribute.
Registering schemes:
Each call like
AddCookie("Cookies")orAddJwtBearer("Bearer")adds a uniquely named scheme.AddAuthentication(defaultScheme)sets the fallback used when no scheme is specified.
Selecting a scheme per endpoint:
Use
[Authorize(AuthenticationSchemes = "Bearer")]to force a specific scheme on a controller/action.Comma-separate names to allow more than one scheme.
Policy schemes: A policy scheme (e.g. via
AddPolicyScheme) can dynamically forward to a real scheme based on the request (e.g. choose JWT when a bearer header is present).Defaults granularity: You can set distinct defaults for authenticate, challenge, and sign-in, useful when mixing cookie and bearer flows.
Q30.
Why is the 'Options Pattern' preferred over injecting IConfiguration directly into your services?
The Options Pattern binds configuration sections to strongly-typed POCOs and injects only the settings a service needs, instead of handing the whole IConfiguration tree to every class.
Strong typing and validation: You get a typed object instead of stringly-typed lookups like
config["Section:Key"], and can validate withValidateDataAnnotations()orValidateOnStart().Separation of concerns: A service depends on its own settings type, not the entire configuration system, so it is easier to test and reason about.
Testability: You can construct
IOptions<T>viaOptions.Create(...)without mockingIConfiguration.Reload support: Use
IOptionsSnapshot<T>(per-request) orIOptionsMonitor<T>(singletons with change notifications) to pick up config changes without restart.
Q31.
Explain the difference between the 'Generic Host' and the 'Minimal Hosting Model' introduced in .NET 6.
The Generic Host is the underlying hosting infrastructure (DI, config, logging, lifetime), while the Minimal Hosting Model is a simplified API surface over that same Generic Host: it is a different way to configure the host, not a different host.
Generic Host:
Built with
Host.CreateDefaultBuilderand (for web)ConfigureWebHostDefaults, typically paired with aStartupclass.More verbose but the explicit, full-control foundation.
Minimal Hosting Model:
Built with
WebApplication.CreateBuilder: one file, noStartup, less ceremony.Sensible defaults (Kestrel, config, logging, DI) preconfigured.
Key relationship:
WebApplicationBuilderstill creates and wraps a Generic Host underneath, so you get the same capabilities with a smaller API.You can still drop down to
builder.Host/builder.WebHostfor advanced configuration.
Q32.
How do you implement global exception handling in .NET 8+ using the IExceptionHandler interface?
In .NET 8+, IExceptionHandler lets you write structured, DI-friendly global exception handling: you implement TryHandleAsync, register the handler, and plug it into the pipeline via UseExceptionHandler().
The contract:
TryHandleAsyncreturnstrueif it handled the exception (response written),falseto pass it on.Multiple handlers run in registration order, forming a chain.
Wiring it up:
Register with
AddExceptionHandler<T>()plusAddProblemDetails().Activate with
app.UseExceptionHandler()early in the pipeline.
Why it's better than middleware: Clean separation, full DI support (inject loggers/services), and pairs naturally with
ProblemDetails.
Q33.
How does the static files middleware work, and how do you serve static content securely in ASP.NET Core?
The static files middleware serves files directly from a known root folder (wwwroot by default) by matching the request path to a physical file, short-circuiting the pipeline before MVC/routing run.
How it works:
You enable it with
app.UseStaticFiles(); it maps request paths to files underIWebHostEnvironment.WebRootPath.On a match it streams the file and sets headers (Content-Type, ETag, Last-Modified) and returns early.
Only files under the web root are served; nothing outside it is reachable by default.
Order matters: Place
UseStaticFiles()early so static requests don't run through auth/MVC unnecessarily, but afterUseRouting()if you need authorization on them.Serving securely:
Never put secrets in
wwwroot: everything there is publicly downloadable.For files needing auth, don't use the middleware; serve via a controller/endpoint that checks authorization and returns
PhysicalFile().Set caching/security headers (
Cache-Control) viaStaticFileOptions.OnPrepareResponse.Unknown file types are not served unless you set
ServeUnknownFileTypes, which is risky; prefer a configuredContentTypeProvider.
Q34.
What is HybridCache (introduced in .NET 9), how does it differ from IDistributedCache, and how does it handle cache stampedes?
HybridCache is a new caching abstraction in .NET 9 that combines a fast in-process (L1) cache with an optional out-of-process (L2) distributed cache, while adding stampede protection and a simpler API. It sits in front of IDistributedCache rather than replacing it.
Two-tier caching:
L1 is in-memory (fast, per-instance); L2 is a distributed backing store (Redis, SQL) via
IDistributedCache.Reads hit L1 first, fall back to L2, then to the factory.
Simpler API than
IDistributedCache:One
GetOrCreateAsynccall replaces the manual get/deserialize/miss/serialize/set pattern.Handles serialization automatically;
IDistributedCacheonly storesbyte[].
Stampede protection (the headline feature):
A cache stampede is many concurrent requests all missing the same key and all hammering the backend to rebuild it.
HybridCachecoalesces concurrent calls for the same key so the factory runs once; the rest await that single result.
Extra features: Tag-based invalidation via
RemoveByTagAsync, and configurable L1/L2 expirations.
Q35.
What is the difference between Constructor Injection and Action Injection using the [FromServices] attribute?
Constructor injection supplies dependencies to the whole class via its constructor; action injection with [FromServices] injects a dependency directly into a single action method parameter. Use the former by default, the latter when only one action needs the service.
Constructor Injection:
Dependency is available to every method in the class and stored in a field.
Best when the service is used across multiple actions; makes dependencies explicit.
Action Injection with
[FromServices]:Resolves the service only for that action, scoped to one method parameter.
Avoids bloating the constructor with a dependency only one action needs.
In .NET 7+ the attribute is often optional, as the framework can infer services from DI.
Trade-off: Action injection hides a dependency at the class level, which can make the class harder to reason about and test if overused.
Q36.
Explain the difference between Transient, Scoped, and Singleton lifetimes. When would you use each?
The three lifetimes control how often the DI container creates an instance: Transient every time it is requested, Scoped once per request (scope), and Singleton once for the application's lifetime.
Transient:New instance every injection/resolution.
Use for lightweight, stateless services; cheap to create and no shared state.
Scoped:One instance per request (per DI scope); shared across that request.
Use for per-request work like
DbContextor unit-of-work services that must see consistent state within a request.
Singleton:One instance for the whole app, shared by all requests and threads.
Use for stateless, thread-safe services or expensive-to-build caches/configuration.
Key rule: Never inject a shorter lifetime into a longer one (avoid captive dependencies), and singletons must be thread-safe.
Q37.
What does the [ApiController] attribute do for a controller?
The [ApiController] attribute opts a controller into a set of conventions tailored for building Web APIs, removing boilerplate you'd otherwise write by hand.
Automatic model validation: If
ModelStateis invalid it returns an automatic400 Bad Requestwith a problem-details body, so you don't checkModelState.IsValidyourself.Binding source inference: Complex types are inferred from the body, simple types from the route/query, so explicit
[FromBody]/[FromRoute]attributes are usually unnecessary.Attribute routing required: Controllers must use attribute routing (e.g.
[Route]); they don't participate in conventional routing.Problem-details error responses: Error status codes are formatted as
ProblemDetails(RFC 7807) by default.Usually paired with
ControllerBase: API controllers inheritControllerBase(no View support) rather thanController.
Q38.
What is Model Binding in ASP.NET Core, and how does it map HTTP request data to action parameters?
Model binding is the process by which ASP.NET Core automatically converts raw HTTP request data (route values, query string, form fields, headers, body) into the strongly-typed parameters of your action methods, so you don't parse the request manually.
Binding sources (in default order):
Form values (POST body), then route data, then query string.
For complex types from the request body, you opt in with
[FromBody](typically JSON).
Explicit source attributes: Override defaults with
[FromRoute],[FromQuery],[FromForm],[FromHeader],[FromBody],[FromServices].How values are matched:
Binding matches by parameter/property name (case-insensitive) and uses type converters to coerce strings into
int,DateTime, enums, etc.Complex objects are bound property-by-property; collections and dictionaries are supported via indexed names.
On failure: A failed conversion doesn't throw: it records an error in
ModelStateand leaves the value at its default, so validation can report it.
Q39.
How can you organize Minimal APIs in a large-scale project to avoid a massive Program.cs file?
Keep Program.cs thin by moving endpoints into feature-grouped extension methods (and route groups), then calling them from the pipeline setup.
Extension methods per feature: Define
MapUserEndpoints(this IEndpointRouteBuilder app)in its own file and callapp.MapUserEndpoints().Route groups for shared config: Use
app.MapGroup("/users")to share a prefix, filters, and metadata across related endpoints.Endpoint group interfaces / conventions: Define an
IEndpointabstraction and auto-register all implementations via reflection or a source generator for consistency.Carter or similar libraries: Community packages like
Carterprovide module-based organization on top of Minimal APIs.
Q40.
What is Swagger/OpenAPI, and how does ASP.NET Core generate API documentation from your endpoints?
OpenAPI is a standard, language-agnostic specification describing your HTTP API; Swagger is the tooling (UI and generators) around it. In ASP.NET Core, a generator inspects your endpoints, routes, and types via reflection to produce a JSON document plus an interactive UI.
OpenAPI vs Swagger: OpenAPI is the spec format; Swagger UI renders it as a browsable, try-it-out page.
Generation: Tooling (
Swashbuckleor the built-inMicrosoft.AspNetCore.OpenApiin .NET 9) reads route templates, HTTP methods, parameters, and DTO shapes to emit the schema.Enriching the docs: Use
[ProducesResponseType]to declare status codes and response types, and XML comments or attributes for descriptions.Why it matters: The spec drives client code generation, contract testing, and live documentation that stays in sync with the code.
Q41.
What is Kestrel, and why is it recommended to use a reverse proxy (like IIS or Nginx) in front of it?
Kestrel is the cross-platform, high-performance default web server built into ASP.NET Core; a reverse proxy is recommended in front of it to add edge concerns and hardening that Kestrel does not focus on.
What Kestrel is:
An ASGI-style, async, event-driven HTTP server that hosts your app process directly.
Runs on Windows, Linux, and macOS and is fast enough to serve traffic on its own.
Why front it with a reverse proxy (
IIS,Nginx,YARP):Security: shields the app, terminates TLS, and helps mitigate slow-client/connection attacks.
Load balancing and serving multiple apps/sites on the same ports.
Operational features: request buffering, caching, compression, static-file serving, port sharing.
Process management and restarts (e.g. the ASP.NET Core Module under IIS).
Note: Kestrel can be exposed directly (edge server) in simple deployments, but a proxy is the conventional production setup.
Q42.
How does session state work in ASP.NET Core, and what are its dependencies on caching and cookies?
Session state stores per-user data on the server across requests, keyed by a session ID that travels in a cookie. The actual data lives in an IDistributedCache, so session depends on both caching and cookies to function.
How it flows:
On first write, a session ID is generated and stored in a cookie sent to the browser.
The data itself is saved server-side in the configured cache, keyed by that ID.
On later requests the cookie returns the ID, and the middleware reloads the data.
Dependency on caching: Session uses
IDistributedCacheas its store; the default in-memory implementation is per-server, so a web farm needs a real distributed cache (Redis, SQL).Dependency on cookies: The cookie holds only an opaque ID, not the data; it is essential (not consent-gated) by default.
Wiring it up:
Register with
AddDistributedMemoryCache()+AddSession(), and addUseSession()to the pipeline before endpoints.Access via
HttpContext.Session; values are stored asbyte[](helpers exist for strings/ints).
Note: Session is non-blocking by default; load explicitly with
LoadAsync()to avoid sync I/O.
Q43.
What is options validation, and why would you use ValidateOnStart()?
Options validation checks that bound configuration values meet your rules (required fields, ranges, custom logic), so misconfiguration fails loudly instead of causing subtle runtime bugs. ValidateOnStart() moves that check to application startup so a bad config crashes the app immediately rather than on first use.
Ways to validate:
Data annotations via
ValidateDataAnnotations()([Required], [Range], etc.).Custom logic via
Validate(...)or anIValidateOptions<T>implementation.
Default timing problem: Without
ValidateOnStart, validation is lazy: it runs only when the options are first resolved, so errors surface late (often on the first request).Why ValidateOnStart(): Fail fast: configuration errors stop the app at boot, which is ideal for catching deployment misconfig before serving traffic.
Q44.
What is the role of WebApplicationBuilder and WebApplication in the Minimal Hosting model?
In the Minimal Hosting model, WebApplicationBuilder handles the configuration/registration phase and WebApplication handles the middleware/run phase: together they collapse the old Program+Startup setup into one streamlined flow.
WebApplicationBuilder(build phase):Created by
WebApplication.CreateBuilder(args).Exposes
Services(DI),Configuration,Logging, andHost/WebHostfor setup.Calling
Build()produces the app.
WebApplication(run phase):Implements both the middleware pipeline (
IApplicationBuilder) and endpoint routing (IEndpointRouteBuilder).You add middleware (
app.UseRouting()) and map endpoints (app.MapGet(...)), then callapp.Run().
About TechPrep
Never walk into a technical interview unprepared again. TechPrep empowers software engineers to stop guessing and start getting offers. We provide the exact questions asked by tech companies across Data Structures & Algorithms, System Design, Low-Level Design & AI coding rounds. Don't leave your career up to chance. Join thousands of engineers who have successfully navigated the tech hiring maze and landed roles at top tech companies.