.NET and ASP.NET Core interview questions and answers

.NET interview questions for backend roles focus on ASP.NET Core and the runtime under it: how the CLR and garbage collector manage memory, dependency injection lifetimes and the captive dependency bug, the middleware pipeline, configuration and the options pattern, EF Core tracking and N+1 queries, and async code that does not starve the thread pool. Senior rounds add hosting, diagnostics and design trade-offs such as minimal APIs versus controllers. Explain what the framework does at run time, not only which method to call.

By Published 10 min read

How .NET interviews are usually run

Most .NET backend loops open with a screen on the language and the runtime, then spend the bulk of the time on ASP.NET Core: how a request flows through the app, how services are wired, how data access works. A practical round is common. You may be asked to build a small Web API with validation and a database behind it, or to review a pull request that hides a lifetime bug, an N+1 query and a blocking call. Senior candidates get a design discussion and production scenarios: memory that keeps growing, latency spikes under load, a deployment that will not start. This page covers the framework and runtime side; questions about C# syntax and object-oriented basics usually come earlier in the loop.

Runtime fundamentals: CLR, JIT and garbage collection

Runtime questions
QuestionWhat it testsWhat a strong answer shows
What happens between dotnet build and your code running?Compilation modelThe compiler emits IL plus metadata into an assembly. At run time the CLR loads it and the JIT compiles methods to native code on first call. Tiered compilation starts with quick code and recompiles hot methods with more optimization. Ahead-of-time options exist for startup-sensitive apps.
.NET Framework versus modern .NET?Platform history.NET Framework is the older Windows-only runtime, still maintained for existing apps. Modern .NET (the line that grew out of .NET Core) is cross-platform, ships side by side, and is where ASP.NET Core and new features live.
How do GC generations work?Memory managementNew objects go to generation 0. Survivors are promoted to 1 and then 2. Most objects die young, so collecting gen 0 often is cheap; full gen 2 collections are expensive. Very large objects go to the large object heap, which is collected with gen 2.
Workstation versus server GC?Runtime configurationServer GC uses a heap and a GC thread per core for throughput and is the usual default for ASP.NET Core. Workstation GC is lighter and suits desktop apps or small containers. Mention that container memory limits influence the choice.
IDisposable versus a finalizer?Resource cleanupDispose releases unmanaged or expensive resources deterministically, via using or await using. A finalizer is a safety net the GC runs later, delays collection of the object, and should be rare. The dispose pattern calls GC.SuppressFinalize once cleanup is done.
Why can a memory leak happen in a garbage-collected runtime?Real leaksSomething still holds a reference: a static collection, an event handler never unsubscribed, a cache with no eviction, or a singleton capturing request data. The GC only frees what is unreachable.
How would you investigate high memory in production?DiagnosticsWatch counters with dotnet-counters (heap size per generation, GC count, allocation rate), take a dump with dotnet-dump or dotnet-gcdump, and compare which types grow between two snapshots.
Runtime questions. Scroll sideways on a small screen.

Dependency injection and service lifetimes

Almost every ASP.NET Core interview asks about lifetimes, because the wrong one causes bugs that pass every unit test. Transient means a new instance each time one is requested. Scoped means one instance per scope, and in a web app a scope is one HTTP request. Singleton means one instance for the life of the app, shared by every request and thread.

  • What is a captive dependency? A longer-lived service holding a shorter-lived one, most often a singleton with a scoped DbContext injected into its constructor. The scoped object is now shared across requests and threads, which in the case of a DbContext means corrupted tracking and threading exceptions.
  • How does the framework catch it? Scope validation, which the default host turns on in the Development environment, throws at startup when a singleton depends on a scoped service. That is why the bug often appears only when someone tests with the Production environment.
  • How do you use a scoped service from a singleton or a background service? Inject IServiceScopeFactory, create a scope per unit of work, resolve the service from it and dispose the scope when done.
  • Is a transient IDisposable a problem? If you resolve it from the root provider, the container keeps it until the app shuts down so it can dispose it. Resolve it from a scope instead.
  • Why should HttpClient come from IHttpClientFactory? Creating and disposing clients per call can exhaust sockets, and one static client for ever can miss DNS changes. The factory pools handlers and rotates them, and typed clients make configuration testable.
  • Constructor injection or service locator? Constructor injection, so dependencies are visible and testable. Resolving from IServiceProvider inside business code hides them.
  • What do keyed services solve? Registering several implementations of one interface and choosing one by key, in versions that support it. Before that, people used factories or named options.
public sealed class OutboxPublisher : BackgroundService
{
    private readonly IServiceScopeFactory _scopes;
    private readonly ILogger<OutboxPublisher> _log;

    public OutboxPublisher(IServiceScopeFactory scopes, ILogger<OutboxPublisher> log)
    {
        _scopes = scopes;
        _log = log;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            using (var scope = _scopes.CreateScope())
            {
                var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
                var batch = await db.OutboxMessages
                    .Where(m => m.SentAt == null)
                    .OrderBy(m => m.CreatedAt)
                    .Take(50)
                    .ToListAsync(stoppingToken);

                // publish, then mark as sent
                await db.SaveChangesAsync(stoppingToken);
            }

            await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
        }
    }
}
A background worker that needs a scoped DbContext. Injecting AppDbContext directly into the constructor would capture one context for the whole app.

The middleware pipeline

Middleware questions
QuestionWhat it testsWhat a strong answer shows
What is middleware?Request pipelineA chain of components, each able to act on the request, call the next one, and act on the response on the way back. Registration order is execution order.
Why does order matter? Give an example.OrderingException handling goes first so it wraps everything. Routing comes before CORS, authentication and authorization, which come before the endpoints. Put authorization before authentication and every protected call fails, because there is no user yet.
Use, Run and Map?Pipeline buildingUse adds middleware that can call next. Run adds a terminal one that never calls next. Map branches the pipeline by path.
How do you short-circuit a request?Control flowWrite the response and do not call next. Static files and health checks do this, which also means later middleware never sees those requests.
Middleware or an MVC filter?ScopeMiddleware sees every request, including ones that never reach MVC. Filters run inside MVC or minimal API endpoints with access to model binding and action metadata. Choose by what context you need.
How would you add a correlation ID to every log line?Practical middlewareMiddleware reads or creates the ID from a header, adds it to the response, and opens a logging scope so every log entry in the request carries it.
Middleware questions. Scroll sideways on a small screen.
public sealed class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<RequestTimingMiddleware> _log;

    public RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> log)
    {
        _next = next;
        _log = log;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var started = Stopwatch.GetTimestamp();
        try
        {
            await _next(context);
        }
        finally
        {
            var elapsed = Stopwatch.GetElapsedTime(started);
            _log.LogInformation("{Method} {Path} -> {Status} in {Ms} ms",
                context.Request.Method, context.Request.Path,
                context.Response.StatusCode, elapsed.TotalMilliseconds);
        }
    }
}
A conventional middleware class that times each request. Register it early with app.UseMiddleware<RequestTimingMiddleware>().

Configuration and the options pattern

  • Where does configuration come from, and which source wins? The default host reads appsettings.json, then the environment-specific file, user secrets in Development, environment variables, then command-line arguments. A later source overrides an earlier one for the same key.
  • How do you set a nested key from an environment variable? Use a double underscore as the section separator, for example ConnectionStrings__Main, because a colon is not valid in variable names on every platform.
  • IOptions, IOptionsSnapshot or IOptionsMonitor? IOptions is read once and fits singletons. IOptionsSnapshot is recomputed per request and is scoped. IOptionsMonitor is a singleton that sees reloads and can notify you of changes.
  • How do you fail fast on bad settings? Bind to a class, add data annotation or custom validation, and validate on start so the app refuses to boot instead of failing on the first request that reads the value.
  • Where should secrets live? Not in appsettings.json in the repo. User secrets locally, then a vault or the platform's secret store in deployed environments, surfaced through a configuration provider.

EF Core questions

Data access with EF Core
QuestionWhat it testsWhat a strong answer shows
What is change tracking and when do you turn it off?TrackingThe context keeps a snapshot of loaded entities and works out UPDATE statements on SaveChanges. For read-only queries, AsNoTracking skips that bookkeeping and is faster and lighter.
What is the N+1 problem in EF Core?Query shapeLoading a list, then triggering one more query per item, usually through lazy loading in a loop. Fix it with Include, or better, a Select projection into exactly the fields the endpoint returns.
When would you use split queries?Cartesian explosionWhen including several collections makes one SQL join return a huge number of duplicated rows. AsSplitQuery runs one query per collection, at the cost of more round trips and no single snapshot.
Why is DbContext scoped, and is it thread-safe?LifetimeIt is a unit of work for one request and is not thread-safe. Two parallel queries on one context throw. Use separate contexts or a context factory for parallel work.
IQueryable versus IEnumerable?Where filtering runsOperators on IQueryable become SQL. Once you call AsEnumerable or ToList, later filters run in memory, which can mean pulling a whole table.
How do migrations get to production?Release processGenerate migrations in development and review them. For production, many teams generate an idempotent SQL script or a migration bundle and run it as a deploy step, rather than calling Migrate() on startup from several instances at once.
How do you handle two users editing the same row?ConcurrencyAdd a concurrency token such as a row version column. SaveChanges throws a concurrency exception when the row changed; you then reload, merge or report the conflict.
Is raw SQL in EF Core safe from injection?SecurityInterpolated-string APIs such as FromSql turn the holes into parameters. Building SQL by concatenation and passing it as a raw string is not safe.
Data access with EF Core. Scroll sideways on a small screen.
// N+1: one query for orders, then one per order when Lines is lazy-loaded
var orders = await db.Orders.Where(o => o.CustomerId == id).ToListAsync(ct);
var result = orders.Select(o => new OrderSummary(o.Id, o.Lines.Sum(l => l.Total)));

// One query, no tracking, only the needed columns
var summaries = await db.Orders
    .Where(o => o.CustomerId == id)
    .Select(o => new OrderSummary(o.Id, o.Lines.Sum(l => l.Total)))
    .ToListAsync(ct);
The N+1 version and the projection that replaces it. The second runs one query and loads only the columns the response needs.

Async and concurrency in ASP.NET Core

  • Why is .Result or .Wait() on a task dangerous in a web app? It blocks a thread pool thread while waiting for work that may itself need a thread pool thread. Under load the pool runs dry, requests queue and latency climbs even though CPU is low. That pattern is called thread pool starvation.
  • Does ASP.NET Core have a synchronization context? No, unlike classic ASP.NET, so the classic deadlock from blocking is less common. The starvation problem remains. ConfigureAwait(false) matters mostly in libraries.
  • How do you honor cancellation? Accept a CancellationToken in the endpoint (bound to the request being aborted) and pass it down to EF Core, HttpClient and any loops.
  • Why avoid async void? Exceptions cannot be awaited or caught by the caller and can crash the process. Use it only for event handlers.
  • How do you run work after returning a response? Not with fire-and-forget Task.Run that captures request services, since the scope is disposed when the request ends. Queue the work to a hosted service with its own scope, or to a message broker.
  • Task or ValueTask? ValueTask avoids an allocation when a method often completes synchronously, such as a cache hit. It must not be awaited twice, so the default for most code stays Task.

Minimal APIs versus controllers

Choosing an API style
AspectMinimal APIsControllers
ShapeEndpoints mapped as lambdas or methods, grouped with route groupsClasses with action methods, routing attributes and conventions
Cross-cutting logicEndpoint filters and route group metadataAction filters, model binding and the full MVC filter pipeline
Typical fitSmall services, microservices, simple CRUD, performance-focused endpointsLarge APIs with many actions, teams used to MVC conventions, heavy use of filters
Interview angleCan you keep it organized as it grows: grouping, extension methods, typed resultsCan you explain the extra machinery and when it earns its place
Choosing an API style. Scroll sideways on a small screen.

A balanced answer says both run on the same routing and hosting stack and can live in one app. The choice is about team conventions and how much of the MVC filter model you need, not about one being modern and the other legacy.

Hosting, deployment and production scenarios

  • What is Kestrel, and do you need a reverse proxy? Kestrel is the cross-platform web server inside ASP.NET Core. It can face the internet directly, but many deployments put IIS, nginx, a load balancer or an ingress in front for TLS termination, routing and limits. Mention forwarded headers so the app sees the real scheme and client IP.
  • In-process versus out-of-process hosting on IIS? In-process runs the app inside the IIS worker for less overhead. Out-of-process runs Kestrel separately with IIS forwarding requests.
  • What is the generic host? The object that owns configuration, logging, DI and hosted services. Web apps and worker services share it, which is why a background worker looks like a web app without endpoints.
  • How do you shut down gracefully? Handle the stopping token in hosted services, let in-flight requests finish within the shutdown timeout, and align that timeout with your orchestrator's termination grace period.
  • How do you expose health to Kubernetes or a load balancer? Health check endpoints, split into liveness (the process is alive) and readiness (dependencies such as the database are reachable).
  • Scenario: latency spikes under load while CPU stays low. Suspect thread pool starvation or a slow dependency. Check thread pool queue length and thread count with dotnet-counters, look for sync-over-async calls, and trace outbound calls for timeouts and missing cancellation.
  • Scenario: the app works locally but returns 500 on every request in staging. Compare environment and configuration (missing connection string, Production-only settings), turn on detailed logging, and remember that scope validation and developer exception pages are Development-only by default.

Fictional example

Answering "Tell me about a production bug you traced in an ASP.NET Core app"
We had intermittent 'a second operation was started on this context' exceptions in a pricing API, only under real traffic. I suspected a lifetime issue because the error is specific to a DbContext used from two threads. I listed the registrations and found a pricing cache registered as a singleton that took the repository, and the repository took the scoped DbContext. Locally nobody saw it because Development validates scopes at startup and that service was only registered in the Production branch of our setup code. I changed the cache to depend on IServiceScopeFactory and open a scope per refresh, then added a test that builds the provider with scope validation on in every environment. The errors stopped, and the test has since caught one more captive dependency in review.

How to prepare for .NET interview questions

  1. Build one small API end to endA minimal API or controller project with EF Core, validation, options bound from configuration, a hosted service and health checks. Being able to explain every line of Program.cs is worth more than reading lists.
  2. Break it on purposeInject a scoped service into a singleton, block on an async call, add lazy loading in a loop. Watch what fails, and learn the error messages and the counters that reveal each problem.
  3. Read your SQLTurn on EF Core logging and look at the queries each LINQ expression produces. Practice explaining tracking, projections and split queries with real output.
  4. Rehearse the scenariosMemory growth, latency under load, a bad deploy, a migration that locks a big table. Answer each out loud in under three minutes: what you check first, what you change, how you confirm.

Mock rounds show you whether your explanation of the middleware order is crisp or rambling. With Natively, an AI interview assistant for Mac and Windows, you can run a practice session on your computer and get a transcript of how you explained lifetimes or EF Core tracking, then compare it with the answer you meant to give. In practice it can also read a C# snippet or a coding task from a screenshot and suggest an approach, so you can compare it with your own review.

Questions people ask

What are common ASP.NET Core interview questions?

Transient, scoped and singleton lifetimes and captive dependencies, middleware order, configuration sources and the options pattern, EF Core tracking and N+1 queries, async pitfalls such as .Result, minimal APIs versus controllers, and Kestrel hosting.

What is a captive dependency in .NET?

A service with a long lifetime holding one with a shorter lifetime, usually a singleton that receives a scoped DbContext. Fix it by injecting IServiceScopeFactory and creating a scope per unit of work.

What EF Core questions come up in .NET interviews?

Change tracking and AsNoTracking, N+1 queries and how Include or projections fix them, split queries, DbContext lifetime and thread safety, IQueryable versus IEnumerable, concurrency tokens and how migrations are applied in production.

Do .NET interviews include a practical task?

Often. Common forms are building a small Web API with a database and validation, or reviewing code for lifetime bugs, blocking async calls and inefficient queries.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP