ASP.NET Core & .NET quiz and interview questions
ASP.NET Core interviews focus on how a request flows through the app (middleware), how services are created (dependency injection lifetimes), how data is loaded (EF Core) and the bugs that only show up in production — wrong middleware order, N+1 queries and singleton DbContexts. Test yourself below.
ASP.NET Core & .NET: key concepts
- Middleware pipeline
- Each request passes through middleware in the order you register them in Program.cs (routing, authentication, authorization, endpoints). Order matters: authentication must run before authorization.
- DI lifetimes
- Transient: a new instance every time. Scoped: one per HTTP request. Singleton: one for the whole app. Never inject a scoped service (like DbContext) into a singleton.
- EF Core loading
- Use Include() or a Select projection to load related data in one query. Lazy loading in a loop causes N+1 queries. Use AsNoTracking() for read-only queries.
- Configuration
- Settings come from appsettings.json, appsettings.{Environment}.json, user secrets, environment variables and the command line — later sources override earlier ones.
- Background work
- BackgroundService (IHostedService) runs long-lived jobs inside the app, such as queues or scheduled tasks, with proper start/stop handling.
- HttpClient
- Use IHttpClientFactory instead of new HttpClient() per call to avoid socket exhaustion and stale DNS.
All 39 ASP.NET Core & .NET questions with answers
Try each one first, then open the answer. Making a class test? Use the test maker.
What is middleware in ASP.NET Core?
- A. A database layer
- B. Components in a pipeline that handle each request and response
- C. A front-end framework
- D. A type of controller
Show answer
B. Components in a pipeline that handle each request and response — Middleware are chained components (logging, auth, routing…). Each can act on the request, call the next one, and act on the response.
A service registered with AddScoped is created…
- A. Once for the whole app
- B. Every time it's requested
- C. Once per HTTP request
- D. Once per user
Show answer
C. Once per HTTP request — Scoped = one instance per request (per DI scope). DbContext is registered as scoped by default.
What is the problem with injecting a scoped service into a singleton?
- A. None
- B. The scoped service is captured and lives for the whole app (captive dependency)
- C. It doubles memory
- D. The singleton becomes scoped
Show answer
B. The scoped service is captured and lives for the whole app (captive dependency) — The singleton keeps the first scoped instance forever, e.g. one DbContext shared across all requests and threads. ASP.NET Core's scope validation throws in Development for this reason.
What is wrong with this Program.cs snippet?
app.UseRouting(); app.UseAuthorization(); app.UseAuthentication(); app.MapControllers();- A. Nothing
- B. Authentication must come before authorization
- C. UseRouting must be last
- D. MapControllers must come first
Show answer
B. Authentication must come before authorization — Authorization needs to know who the user is, so UseAuthentication() has to run first. In this order, [Authorize] endpoints see an anonymous user.
When should you use AsNoTracking() in EF Core?
- A. When you will update the entities
- B. For read-only queries, to skip change tracking and run faster
- C. Never in production
- D. Only with stored procedures
Show answer
B. For read-only queries, to skip change tracking and run faster — Tracking keeps a snapshot of every loaded entity for SaveChanges. For lists or reports you won't modify, AsNoTracking() saves memory and CPU.
With lazy loading on, what's the problem here?
var orders = db.Orders.ToList(); foreach (var o in orders) Console.WriteLine(o.Customer.Name);- A. Compile error
- B. One extra query per order (N+1 queries)
- C. Customer is always null
- D. Nothing — it's efficient
Show answer
B. One extra query per order (N+1 queries) — Each o.Customer access runs a separate query: 1 for orders + N for customers. Use .Include(o => o.Customer) or project only the fields you need.
What is Kestrel?
- A. A logging library
- B. ASP.NET Core's built-in cross-platform web server
- C. An ORM
- D. A testing tool
Show answer
B. ASP.NET Core's built-in cross-platform web server — Kestrel is the default web server inside every ASP.NET Core app. It's often placed behind a reverse proxy like IIS or Nginx in production.
What is BackgroundService (IHostedService) used for?
- A. Rendering views
- B. Running long-lived background jobs inside the app with clean start/stop
- C. Hosting static files
- D. Replacing controllers
Show answer
B. Running long-lived background jobs inside the app with clean start/stop — Good for queue consumers, scheduled clean-ups or polling jobs. The host starts it with the app and signals cancellation on shutdown.
A setting exists in appsettings.json and as an environment variable. Which value wins by default?
- A. appsettings.json
- B. The environment variable
- C. Whichever is shorter
- D. The app throws an error
Show answer
B. The environment variable — The default builder adds environment variables after the JSON files, and later providers override earlier ones. Command-line args override both.
Why use IHttpClientFactory instead of new HttpClient() on every call?
- A. It's required by law
- B. It avoids socket exhaustion and handles DNS changes by pooling handlers
- C. It makes requests synchronous
- D. It encrypts traffic
Show answer
B. It avoids socket exhaustion and handles DNS changes by pooling handlers — Creating and disposing HttpClient per request leaves sockets in TIME_WAIT. The factory reuses handlers and rotates them so DNS changes are picked up.
A browser requests GET /hello/Ali. What is the response body?
app.MapGet("/hello/{name}", (string name) => $"Hi {name}");- A. Hi {name}
- B. Hi Ali
- C. 404 Not Found
- D. Hello Ali
Show answer
B. Hi Ali — Minimal APIs bind the {name} route value to the name parameter, and the interpolated string becomes "Hi Ali".
What's wrong with this registration?
builder.Services.AddSingleton<AppDbContext>();- A. Nothing
- B. DbContext isn't thread-safe; a singleton is shared by all requests at once
- C. It should be AddTransient for speed
- D. Singletons can't take constructor parameters
Show answer
B. DbContext isn't thread-safe; a singleton is shared by all requests at once — One DbContext shared across concurrent requests causes threading errors and a change tracker that grows forever. Use AddDbContext (scoped).
What does the [ApiController] attribute add?
- A. Database access
- B. Automatic 400 responses for invalid models and smarter parameter binding
- C. Authentication
- D. Response caching
Show answer
B. Automatic 400 responses for invalid models and smarter parameter binding — It turns on model-validation 400s, infers [FromBody]/[FromRoute] binding sources and requires attribute routing.
Your API runs on three servers. Which cache keeps data consistent across all of them?
- A. IMemoryCache
- B. IDistributedCache (e.g. Redis)
- C. Static variables
- D. Session state in memory
Show answer
B. IDistributedCache (e.g. Redis) — IMemoryCache lives inside one process, so each server has its own copy. A distributed cache like Redis is shared by every instance.
What is the role of Program.cs in a modern ASP.NET Core app?
- A. Only holds the Main method
- B. Builds the host: registers services, configures middleware and starts the app
- C. Defines database tables
- D. Contains the views
Show answer
B. Builds the host: registers services, configures middleware and starts the app — Since .NET 6, minimal hosting puts builder.Services… and app.Use… together in Program.cs (no Startup.cs needed).
What is the difference between app.Use and app.Run?
- A. None
- B. Use adds middleware that can call the next one; Run is terminal and ends the pipeline
- C. Run adds services
- D. Use only works for static files
Show answer
B. Use adds middleware that can call the next one; Run is terminal and ends the pipeline — app.Run(context => …) never calls next, so anything registered after it is never reached.
What is written to the response?
app.Use(async (ctx, next) => { await ctx.Response.WriteAsync("A"); await next(); await ctx.Response.WriteAsync("C"); }); app.Run(async ctx => await ctx.Response.WriteAsync("B"));- A. ABC
- B. ACB
- C. BAC
- D. AB
Show answer
A. ABC — The first middleware writes A, calls the next (which writes B), then writes C on the way back out.
Which lifetime creates a new instance every time a service is requested?
- A. Singleton
- B. Scoped
- C. Transient
- D. Static
Show answer
C. Transient — Transient suits lightweight, stateless services. Scoped = one per request, Singleton = one for the app.
What is the Options pattern (IOptions<T>)?
- A. A UI dropdown
- B. Binding a configuration section to a strongly typed class injected where needed
- C. A feature flag service
- D. A logging setting
Show answer
B. Binding a configuration section to a strongly typed class injected where needed — builder.Services.Configure<SmtpSettings>(config.GetSection("Smtp")) then inject IOptions<SmtpSettings>.
Where should secrets like API keys go during local development?
- A. appsettings.json in Git
- B. User Secrets (or environment variables), never committed to source control
- C. Hard-coded in Program.cs
- D. In wwwroot
Show answer
B. User Secrets (or environment variables), never committed to source control — In production use environment variables or a vault such as Azure Key Vault.
How does ASP.NET Core know which environment it's running in?
- A. The machine name
- B. The ASPNETCORE_ENVIRONMENT (or DOTNET_ENVIRONMENT) variable — Development, Staging, Production
- C. The port number
- D. A database row
Show answer
B. The ASPNETCORE_ENVIRONMENT (or DOTNET_ENVIRONMENT) variable — Development, Staging, Production — It also decides which appsettings.{Environment}.json is loaded and whether the developer exception page shows.
What does ILogger<T> give you?
- A. A database
- B. Structured logging tied to a category (T), sent to configured providers like console, files or Application Insights
- C. Error pages
- D. Caching
Show answer
B. Structured logging tied to a category (T), sent to configured providers like console, files or Application Insights — Use message templates: _log.LogInformation("Order {OrderId} paid", id) — not string concatenation.
What's wrong with this logging call?
_logger.LogInformation($"User {user.Email} logged in with password {password}");- A. Nothing
- B. It logs a password (sensitive data) and uses interpolation instead of a message template
- C. LogInformation doesn't exist
- D. Emails can't be logged
Show answer
B. It logs a password (sensitive data) and uses interpolation instead of a message template — Never log secrets. Write _logger.LogInformation("User {UserId} logged in", user.Id).
What are health checks (MapHealthChecks) for?
- A. Checking user health data
- B. An endpoint load balancers and monitors call to see if the app and its dependencies are working
- C. Unit testing
- D. Logging
Show answer
B. An endpoint load balancers and monitors call to see if the app and its dependencies are working — e.g. /health reports Healthy/Unhealthy, including database or Redis checks.
What does UseStaticFiles() serve?
- A. Razor views
- B. Files from wwwroot such as CSS, JS and images
- C. Database files
- D. Configuration
Show answer
B. Files from wwwroot such as CSS, JS and images — Place it early in the pipeline so static files are served without hitting MVC.
What do minimal APIs offer compared with controllers?
- A. Nothing new
- B. Less ceremony — map endpoints directly with lambdas, great for small or fast APIs
- C. No dependency injection
- D. No routing
Show answer
B. Less ceremony — map endpoints directly with lambdas, great for small or fast APIs — app.MapGet("/orders/{id}", (int id, IOrderService s) => s.Get(id)) — DI and binding still work.
How are authentication and authorization different?
- A. Same thing
- B. Authentication = who you are; authorization = what you're allowed to do
- C. Authorization comes first
- D. Authentication handles roles
Show answer
B. Authentication = who you are; authorization = what you're allowed to do — Cookies or JWT establish identity; [Authorize(Policy = "CanEdit")] decides access.
What is policy-based authorization?
- A. Using only roles
- B. Named rules (e.g. "Over18", "CanApproveInvoices") built from requirements and handlers
- C. Firewall rules
- D. Password policies
Show answer
B. Named rules (e.g. "Over18", "CanApproveInvoices") built from requirements and handlers — Policies keep complex rules in one place: [Authorize(Policy = "CanApproveInvoices")].
What does Kestrel usually sit behind in production on Linux?
- A. Nothing
- B. A reverse proxy like Nginx (or a load balancer)
- C. IIS only
- D. A CDN only
Show answer
B. A reverse proxy like Nginx (or a load balancer) — The proxy handles TLS, compression and load balancing, forwarding requests to Kestrel.
What is a self-contained deployment?
- A. An app with no dependencies
- B. Publishing the app together with the .NET runtime, so the server doesn't need .NET installed
- C. A Docker image only
- D. A single source file
Show answer
B. Publishing the app together with the .NET runtime, so the server doesn't need .NET installed — dotnet publish --self-contained -r linux-x64 — bigger output, but no shared runtime required.
What does output caching / response compression middleware help with?
- A. Security
- B. Performance — fewer recomputed responses and smaller downloads
- C. Logging
- D. Routing
Show answer
B. Performance — fewer recomputed responses and smaller downloads — AddResponseCompression() gzips/brotlis responses; output caching (.NET 7+) stores whole responses server-side.
What does CancellationToken in an action parameter give you?
- A. Nothing
- B. It's cancelled when the client disconnects, so you can stop expensive work early
- C. It cancels other users' requests
- D. Required for async
Show answer
B. It's cancelled when the client disconnects, so you can stop expensive work early — Pass it down to EF Core and HttpClient calls: await _db.Orders.ToListAsync(ct).
What is SignalR used for?
- A. Database migrations
- B. Real-time messages from server to browser (chat, live dashboards, notifications)
- C. Logging
- D. Static files
Show answer
B. Real-time messages from server to browser (chat, live dashboards, notifications) — It uses WebSockets when available and falls back to other transports.
What is the main idea of a Docker container for an ASP.NET Core app?
- A. A virtual machine with its own OS kernel
- B. A packaged, isolated runtime environment so the app runs the same everywhere
- C. A build server
- D. A database
Show answer
B. A packaged, isolated runtime environment so the app runs the same everywhere — The image includes the app and the runtime; containers share the host kernel, so they start fast.
Which command creates a new web API project?
- A. dotnet run webapi
- B. dotnet new webapi
- C. dotnet build api
- D. npm init api
Show answer
B. dotnet new webapi — dotnet new lists templates like webapi, mvc, razor and blazor.
What is Razor Pages?
- A. A CSS framework
- B. A page-focused model where each page (.cshtml) has its own PageModel instead of controllers
- C. Blazor's other name
- D. A testing tool
Show answer
B. A page-focused model where each page (.cshtml) has its own PageModel instead of controllers — Good for form-heavy sites: Pages/Contact.cshtml + Contact.cshtml.cs with OnGet/OnPost handlers.
What is the difference between Blazor Server and Blazor WebAssembly?
- A. None
- B. Server runs components on the server over a SignalR connection; WebAssembly runs .NET in the browser
- C. WebAssembly needs IIS
- D. Server runs offline
Show answer
B. Server runs components on the server over a SignalR connection; WebAssembly runs .NET in the browser — .NET 8 also lets you mix render modes per component (static SSR, server, WebAssembly).
How do you run a recurring job (e.g. every night) inside an ASP.NET Core app?
- A. Thread.Sleep in a controller
- B. A BackgroundService with a timer (PeriodicTimer), or a scheduler like Hangfire/Quartz
- C. A JavaScript setInterval
- D. A database trigger
Show answer
B. A BackgroundService with a timer (PeriodicTimer), or a scheduler like Hangfire/Quartz — For reliability across restarts and multiple servers, use a persistent scheduler.
Why add rate limiting and request size limits to a public ASP.NET Core API?
- A. SEO
- B. To protect against abuse and denial-of-service style overload
- C. To speed up JSON
- D. To enable CORS
Show answer
B. To protect against abuse and denial-of-service style overload — builder.Services.AddRateLimiter(...) plus sensible MaxRequestBodySize keep one client from exhausting resources.
More subjects
Need software for your business instead? I'm an AI automation & full-stack developer — see what I build.