200 ASP.NET Core Full Stack Interview Questions and Answers

200 ASP.NET Core Full Stack Interview Questions and Answers

Interview Preparation Guide

200 ASP.NET Core Full Stack Interview Questions & Answers

From modern C# 12 and .NET 8/9 internals to EF Core, SQL Server, Dapper, JWT, Redis, SignalR, Blazor, React, testing and distributed microservices architecture.

200Questions
20Core Levels
20Video Parts
3Difficulty Levels

What You’ll Cover

Level: Beginner → Intermediate → Advanced → Enterprise Architect

Technologies covered:

C# 12 & .NET 8 / .NET 9 FundamentalsCommon Language Runtime ( CLR ) & Garbage CollectionAsynchronous Programming ( async / await , Task , ValueTask )Modern C# (Records, Pattern Matching, Primary Constructors)ASP.NET Core Architecture, Hosting & KestrelDependency Injection (Lifetimes, Keyed Services, Captive Dependencies)Middleware Pipeline & Global Error Handling ( ProblemDetails , IExceptionHandler )RESTful Web APIs, Routing & Minimal APIsModel Binding, Validation (FluentValidation) & Action FiltersEntity Framework Core ( DbContext , Change Tracker, Migrations, Query Splitting)Advanced EF Core Performance (Compiled Queries, Bulk Operations, Interceptors)SQL Server Database Engineering (Indexes, SARGable Queries, ACID, Isolation Levels)Dapper Micro-ORM & High-Performance Data AccessAuthentication, Identity & JSON Web Tokens (JWT)Authorization (Role-Based, Claims-Based, Policy-Based & Resource-Based)Web Security & Cryptography (XSS, CSRF, SQLi, Data Protection API, Rate Limiting)In-Memory & Distributed Caching ( IMemoryCache , Redis, Cache-Aside, HybridCache )Real-Time Communication with SignalR (Hubs, Backplanes, WebSockets )Frontend Integration (React, Next.js, Blazor United & BFF Architecture)Automated Testing ( xUnit , NSubstitute , WebApplicationFactory , Testcontainers )Microservices, API Gateways ( YARP ), MassTransit , RabbitMQ & Distributed System Design
Level 1

C# Language Fundamentals & Memory Architecture

10 Questions
1

What is the .NET CLR and how does execution work?

The Common Language Runtime (CLR) is the execution engine for .NET applications.

C# source code is first compiled by Roslyn into Common Intermediate Language (CIL) bytecode.

At runtime, the Just-In-Time (JIT) compiler converts CIL into architecture-specific machine code.

The CLR provides essential services including garbage collection, type safety verification, thread management, and structured exception handling.

2

What is the difference between Value Types and Reference Types in C#?

Value types directly contain their data and are typically allocated on the thread execution stack.

Reference types store a memory address pointing to the actual object allocated on the managed heap.

Value types derive from System.ValueType and include primitive types, structs, and enums.

Reference types include classes, interfaces, delegates, records, and strings.

Copying a value type duplicates the underlying data, while copying a reference type creates an additional pointer to the same heap object.

3

What is Boxing and Unboxing and why is it a performance concern?

Boxing is the implicit conversion of a value type to an object or interface reference type on the heap.

Unboxing is the explicit extraction of the value type from the boxed heap object back onto the stack.

Boxing allocates heap memory and incurs garbage collection pressure.

Unboxing requires runtime type verification and memory copy operations.

Modern C# minimizes boxing through generics such as List<T> instead of non-generic ArrayList collections.

4

Why are strings immutable in C# and what is the role of StringBuilder ?

String objects cannot be modified once created in memory.

Any string modification creates a brand new string instance on the managed heap.

Immutability provides thread safety, security for sensitive data, and enables string interning in the CLR.

When concatenating multiple strings inside loops, repeated heap allocations degrade performance.

StringBuilder provides a mutable buffer that dynamically expands, preventing unnecessary memory allocations.

5

What are the differences between ref, out, and in parameters?

The ref keyword passes an argument by reference, requiring the variable to be initialized before passing.

The out keyword passes an argument by reference for returning multiple values, requiring the method to assign a value before returning.

The in keyword passes an argument by reference but prevents the called method from modifying its value.

Using in avoids expensive copying of large readonly value types while maintaining immutability.

6

How do Nullable Reference Types work in modern C#?

Nullable Reference Types were introduced in C# 8 to eliminate NullReferenceException bugs at runtime.

Reference types are non-nullable by default when nullable context is enabled.

A question mark syntax indicates that a reference may legitimately hold a null value.

The Roslyn compiler performs static flow analysis to warn developers when dereferencing potentially null variables.

The null-forgiving operator overrides compiler warnings when the developer guarantees a value is not null.

7

How does Garbage Collection work in .NET?

The .NET Garbage Collector automatically manages memory by reclaiming heap objects no longer reachable by roots.

Heap memory is divided into three generational segments: Generation 0, Generation 1, and Generation 2.

Generation 0 holds short-lived newly allocated objects.

Surviving objects promote to Generation 1 and eventually to Generation 2 for long-lived application state.

Large objects greater than 85,000 bytes allocate directly on the Large Object Heap to reduce compaction overhead.

8

What is the difference between IDisposable and Finalizers?

IDisposable provides deterministic cleanup of unmanaged resources such as file handles, database connections, and sockets.

The consumer calls the Dispose method explicitly or deterministically through the using statement.

Finalizers provide nondeterministic cleanup invoked by the GC finalizer thread before reclaiming object memory.

Implementing the standard Dispose pattern suppresses finalization via GC.SuppressFinalize when Dispose is called.

9

What are Delegates and how do Func and Action simplify them?

A delegate is a type-safe function pointer referencing one or more methods with a matching signature.

Delegates enable callback architectures, event-driven programming, and LINQ expression processing.

Action represents a built-in generic delegate that accepts parameters and returns void.

Func represents a built-in generic delegate that accepts parameters and returns a designated result value.

Func and Action eliminate the need to declare custom delegate types across application code.

10

What is the difference between Struct and Class in C#?

A class is a reference type allocated on the heap supporting full inheritance hierarchies.

A struct is a lightweight value type allocated inline on the stack that cannot inherit from classes.

Structs should represent small, immutable data structures smaller than 16 bytes in size.

Classes are suitable for complex domain models requiring identity, lifecycle management, and inheritance.

Level 2

Advanced C# OOP & Collections

10 Questions
11

What is the difference between Method Overloading and Method Overriding?

Method overloading occurs within the same class with identical names but differing parameter lists.

Overloading is resolved at compile time through static polymorphism.

Method overriding occurs when a derived class replaces a base class method marked virtual or abstract.

Overriding is resolved at runtime through dynamic polymorphism using the virtual method table.

The override keyword is mandatory in derived classes to replace base method behavior.

12

What is the difference between new and override keywords in method declaration?

The override keyword extends and replaces a base class virtual method implementation dynamically.

The new keyword hides an inherited base member without replacing it in the virtual method table.

Calling an overridden method through a base class reference executes the derived class implementation.

Calling a hidden method through a base class reference executes the base class implementation.

Hiding members without the new modifier produces a compiler warning.

13

What is the difference between an Abstract Class and an Interface?

An abstract class is an incomplete base class that can contain state, instance fields, and non-public constructors.

An interface defines a behavioral contract that supporting classes must implement.

A C# class can inherit from only one abstract class but can implement multiple interfaces.

Abstract classes model core identity relationships, while interfaces model shared capabilities across unrelated classes.

Modern C# supports default interface methods for backward-compatible API evolution.

14

What are Generics in C# and how do constraints work?

Generics allow classes, interfaces, and methods to be parameterized by data types without sacrificing type safety.

The CLR generates specialized native machine code for each value type, preventing boxing and casting overhead.

Generic constraints restrict the type arguments a consumer can supply using the where clause.

Common constraints include where T : class, where T : struct, where T : new(), and interface constraints.

Constraints allow the compiler to verify member access on generic parameters safely.

15

What is the difference between IEnumerable , ICollection , and IList ?

IEnumerable is the foundational interface supporting forward-only iteration via GetEnumerator.

ICollection inherits from IEnumerable and adds count tracking, thread safety properties, and mutating methods.

IList inherits from ICollection and provides index-based element access and insertion.

Exposing IEnumerable communicates read-only deferred enumeration to calling code.

Exposing IList allows random access and direct modification of items by numeric index.

16

What is the difference between List and Array in C#?

An array is a fixed-size, contiguous memory structure allocated once with a permanent length.

A List is a dynamically resizing collection backed internally by an expanding array.

When a List reaches capacity, it allocates a new backing array twice the size and copies elements over.

Arrays provide the lowest memory overhead and direct index performance for fixed-size datasets.

Lists provide convenient dynamic collection manipulation for unpredictable data quantities.

17

How does Dictionary work internally in C#?

Dictionary uses an array of buckets and an array of entries to provide constant-time key lookup.

When a key is added, GetHashCode computes a hash code mapped to a specific bucket index.

Hash collisions are resolved by chaining entries with identical bucket assignments.

When the collection load factor exceeds threshold limits, the internal arrays resize and rehash entries.

Properly overriding GetHashCode and Equals is required when using custom objects as dictionary keys.

18

What is the difference between HashSet and List ?

A List preserves insertion order, allows duplicate elements, and performs lookups in linear time.

A HashSet stores unique elements only, ignores duplicates, and performs lookups in constant time.

HashSet uses hash table mechanics to verify whether an item exists without scanning every element.

Use List when element ordering matters and duplicates are valid domain data.

Use HashSet for fast membership tests and mathematical set operations such as unions and intersections.

19

What is Covariance and Contravariance in C# Generics?

Covariance allows using a more derived type than originally specified, declared using the out keyword.

Contravariance allows using a less derived type than originally specified, declared using the in keyword.

Covariance applies to output positions such as method return types in IEnumerable.

Contravariance applies to input positions such as parameters in Action and IComparer.

Variance preservation provides safe polymorphic assignment across generic interface boundaries.

20

What is an Exception Filter in C# and why is it beneficial?

Exception filters use the when keyword on a catch block to inspect exception state before handling it.

The catch block only executes if the filter condition evaluates to true.

Exception filters inspect exceptions without unwinding the stack if the condition evaluates to false.

Leaving the stack intact preserves the original call stack diagnostics in crash logs and crash dumps.

Level 3

Asynchronous Programming & Concurrency

10 Questions
21

What is the difference between Synchronous, Asynchronous, and Multithreaded execution?

Synchronous execution blocks the current thread until the requested operation completes.

Asynchronous execution releases the calling thread while awaiting an I/O operation to complete.

Multithreading uses multiple operating system threads to execute CPU-bound work concurrently.

Asynchronous I/O uses OS completion ports rather than occupying background threads.

Asynchronous programming optimizes server scalability, while multithreading optimizes parallel CPU calculations.

22

How do async and await work under the hood in C#?

The async keyword instructs the Roslyn compiler to transform the method into an asynchronous state machine.

The state machine implements IAsyncStateMachine to manage execution steps and captured variables.

When execution encounters an await keyword, it checks if the awaited task is already completed.

If incomplete, the method registers a continuation callback and yields execution back to the caller.

When the operation completes, the continuation resumes execution at the correct state machine stage.

23

What is the difference between Task and ValueTask ?

Task is a reference type allocated on the managed heap representing an asynchronous operation.

ValueTask is a lightweight value type struct that avoids heap allocation when operations complete synchronously.

If an asynchronous method frequently returns results from a memory cache, ValueTask avoids allocation overhead.

ValueTask must only be awaited once and should never be used with Task.WhenAll or Task.WhenAny.

Standard Task should remain the default choice unless profiling proves allocation bottlenecks.

24

Why should you avoid async void in C#?

Async void methods cannot be awaited because they return no awaitable Task instance to calling code.

Any unhandled exception thrown inside an async void method crashes the application process immediately.

Callers cannot track operation completion, complicating unit tests and orchestration logic.

Async void should exclusively be used for top-level UI event handlers where the framework requires a void signature.

All application service and controller methods must return Task or Task<T>.

25

What causes async deadlocks with .Result and .Wait()?

Accessing .Result or calling .Wait() synchronously blocks the calling thread waiting for task completion.

In environments with a SynchronizationContext, awaiting tasks schedule their continuations back to the original thread.

If the original thread is blocked waiting for .Result, the continuation cannot gain execution access.

The blocked thread waits for the task, while the task waits for the thread, causing a permanent deadlock.

Always use await asynchronously instead of blocking synchronously on Task results.

26

What is ConfigureAwait (false) and when should it be used?

ConfigureAwait(false) instructs the task awaiter not to marshal the continuation back to the original SynchronizationContext.

The continuation resumes on any available thread pool thread rather than waiting for the original context.

Using ConfigureAwait(false) improves performance and eliminates deadlock risks in class libraries.

ASP.NET Core does not have a SynchronizationContext, making ConfigureAwait(false) optional in web applications.

It remains standard best practice inside reusable cross-platform NuGet libraries.

27

How does CancellationToken work across async pipelines?

CancellationToken provides cooperative cancellation across asynchronous operations and distributed HTTP requests.

A CancellationTokenSource creates the token and issues cancellation signals via Cancel or CancelAfter.

Async methods pass the token to downstream APIs and periodically call ThrowIfCancellationRequested.

When an HTTP client aborts a request, ASP.NET Core cancels the request token automatically.

Passing tokens prevents servers from wasting database and CPU resources on abandoned client requests.

28

What is Task.WhenAll vs Task.WaitAll ?

Task.WhenAll is an asynchronous method returning a Task that completes when all supplied tasks finish.

Task.WaitAll is a synchronous blocking method that stalls the calling thread until all tasks complete.

Task.WhenAll preserves non-blocking async execution and aggregates all caught exceptions into an AggregateException.

Task.WaitAll wastes thread pool capacity and increases deadlock hazards in web services.

Use Task.WhenAll with await to process independent external API calls in parallel.

29

How does SemaphoreSlim differ from the lock statement?

The lock statement relies on Monitor to synchronize access across threads for synchronous code.

Lock cannot be used inside asynchronous code because it cannot be held across await boundaries.

SemaphoreSlim is a lightweight synchronization primitive that supports non-blocking asynchronous waiting via WaitAsync.

SemaphoreSlim can also limit concurrency to a specified number of concurrent resource consumers.

Always release SemaphoreSlim inside a finally block to ensure locks are never orphaned.

30

What is ThreadPool starvation and how can it be avoided?

ThreadPool starvation occurs when all available worker threads are blocked waiting on synchronous operations.

The runtime throttles the injection of new threads to a slow rate of roughly one thread per second.

Incoming HTTP requests queue up rapidly, causing severe latency spikes and complete application unresponsiveness.

Starvation is caused by blocking async code using .Result, .Wait(), or Task.Delay without await.

It is prevented by ensuring pure asynchronous patterns throughout the entire request call stack.

Level 4

Modern C# Features & LINQ Internals

10 Questions
31

What is the difference between IEnumerable and IQueryable in LINQ?

IEnumerable executes queries in memory using LINQ to Objects with in-process delegate evaluation.

IQueryable executes queries out-of-process by parsing an Expression Tree into provider-specific syntax such as SQL.

IEnumerable filters data after bringing all rows into server memory.

IQueryable translates filter expressions into SQL WHERE clauses executed directly on the database engine.

Use IQueryable when querying databases and IEnumerable when evaluating in-memory collections.

32

What is Deferred Execution in LINQ and how does it work?

Deferred execution means a query is not executed when defined; it runs only when enumerated.

Methods like Where, Select, and Take return iterator pipelines that construct query definitions.

Execution triggers when consuming data via foreach, ToList, ToArray, Count, or FirstOrDefault.

Deferred execution allows queries to be composed dynamically across multiple application layers.

Re-enumerating a deferred query executes the database command again unless materialized with ToList.

33

What are Expression Trees in C#?

An Expression Tree represents executable code as a structured in-memory data tree of nodes.

Instead of compiling a lambda into CIL bytecode, the compiler generates an Expression<Func<T>> data structure.

Entity Framework Core analyzes expression tree nodes to translate C# logic into relational SQL commands.

Expression trees allow code inspection, query modification, and runtime dynamic query generation.

Compiling an expression tree via Compile produces an executable delegate for in-memory execution.

34

What is the difference between First, FirstOrDefault , Single, and SingleOrDefault ?

First returns the first matching element or throws an InvalidOperationException if none match.

FirstOrDefault returns the first matching element or default value if no match is found.

Single returns the unique matching element and throws if none or more than one match exists.

SingleOrDefault returns the unique element, default if none exist, and throws if multiple matches exist.

Use SingleOrDefault when asserting business uniqueness and FirstOrDefault for general item lookups.

35

What are Record Types and how do they differ from Classes?

Records are reference types designed for immutable data models with built-in value-based equality semantics.

Two record instances with identical property values evaluate as equal using Equals and the equality operator.

Records automatically synthesize equality methods, GetHashCode, ToString formatting, and deconstructors.

The with expression enables non-destructive mutation by creating a modified copy of an existing record.

Record structs provide value-type equivalents for zero-allocation domain representations.

36

What are Pattern Matching enhancements in modern C#?

Pattern matching tests values against shapes and extracts data conditionally in a concise syntax.

Modern C# supports declaration patterns, type patterns, relational patterns (<, >), and logical patterns (and, or, not).

Switch expressions replace verbose switch statements with concise expression-based mappings.

Property patterns match nested object properties directly without manual null checks.

Pattern matching improves readability and eliminates repetitive casting operations across business logic.

37

What are Primary Constructors in C# 12?

Primary constructors allow declaring constructor parameters directly on class and struct headers.

Constructor parameters are in scope throughout the entire class declaration body.

They eliminate repetitive boilerplate field declarations and manual assignments in constructors.

Primary constructor parameters can initialize properties, fields, or be passed directly to base class constructors.

They are widely used in modern ASP.NET Core for concise dependency injection syntax.

38

What is the difference between Span and Memory?

Span<T> is a ref struct providing contiguous, type-safe representation of arbitrary memory regions on the stack.

Because Span<T> is a stack-only ref struct, it cannot be boxed, stored on the heap, or used across async boundaries.

Memory<T> is a heap-allocatable struct representing memory that can survive across asynchronous await operations.

Span and Memory allow slicing arrays and strings without allocating new substring buffers on the heap.

They form the performance foundation of high-throughput ASP.NET Core web servers and parsers.

39

What are Default Interface Methods and why were they added?

Default interface methods allow defining concrete method implementations directly on interface declarations.

They allow API authors to extend existing interfaces with new methods without breaking existing implementing classes.

Classes that implement the interface can use the default implementation or override it with custom logic.

They bridge interop requirements with Android and Swift interfaces and enable traits-based design.

Stateful data remains prohibited on interfaces; only behavior can have default implementations.

40

What is String Interning and the String.Intern method?

String interning is an optimization where the CLR maintains a single system-wide table of unique string literals.

All identical string literals declared in source code reference the exact same memory address on the heap.

Comparing interned strings requires a simple reference equality check rather than scanning character arrays.

The String.Intern method explicitly registers dynamically constructed runtime strings into the intern pool.

Interning dynamic strings consumes permanent memory and should only be applied to heavily duplicated keys.

Level 5

ASP.NET Core Architecture & Hosting

10 Questions
41

What is the ASP.NET Core Hosting Model and WebApplicationBuilder ?

ASP.NET Core uses a generic hosting model that bootstraps application configuration, logging, and dependency injection.

WebApplicationBuilder configures application services, environment profiles, and configuration sources.

Calling builder.Build() compiles the dependency injection container and constructs the WebApplication instance.

The WebApplication instance configures the HTTP request processing pipeline through middleware components.

Calling app.Run() starts the underlying web server and listens for incoming HTTP requests.

42

What is Kestrel and how does it compare to IIS and NGINX?

Kestrel is a cross-platform, event-driven, high-performance web server included by default in ASP.NET Core.

Kestrel processes HTTP/1.1, HTTP/2, and HTTP/3 requests directly with high socket efficiency.

In enterprise deployments, Kestrel often sits behind reverse proxies like IIS, NGINX, YARP, or Apache.

Reverse proxies provide edge security, TLS termination, static file compression, and public routing.

Kestrel can also run as an internet-facing edge server in containerized Kubernetes environments.

43

How does the ASP.NET Core Middleware Pipeline work?

Middleware components assemble into an execution pipeline to handle HTTP requests and responses.

Each middleware component executes incoming logic, calls next() to pass control, and executes outgoing logic.

The sequence in which middleware is registered in Program.cs strictly determines the order of execution.

Short-circuiting occurs when a middleware returns an HTTP response without invoking the next delegate.

Examples include authentication, authorization, routing, CORS, and exception handling middleware.

44

What is the difference between app.Use and app.Run in Middleware?

app.Use registers a middleware component that can inspect the request and invoke the next middleware in line.

app.Run registers a terminal middleware that handles the request and terminates the pipeline execution.

Terminal middleware never invokes a next delegate because it sits at the end of the request chain.

app.Map conditionally branches the middleware pipeline based on specified URL request paths.

Use app.Use for pipeline filters and app.Run for endpoint responders.

45

What is the difference between In-Process and Out-of-Process hosting in IIS ?

In-process hosting runs the ASP.NET Core application inside the IIS worker process (w3wp.exe).

Out-of-process hosting runs the application in an independent Kestrel process, with IIS acting as a reverse proxy.

In-process hosting provides significantly higher throughput by bypassing loopback network communication.

Out-of-process hosting isolates application crashes from the IIS master process but introduces IPC latency.

In-process hosting is the standard default configuration when deploying to Windows IIS environments.

46

What is the role of Program.cs in modern .NET 6/8/9?

Modern .NET consolidates the legacy Program.cs and Startup.cs into a single unified Program.cs file.

It leverages C# Top-Level Statements to eliminate verbose class, namespace, and Main method declarations.

Services are registered directly on builder.Services using the built-in dependency injection container.

Middleware and route endpoints are registered directly on the resulting app instance.

This unified pattern simplifies bootstrapping while retaining full access to all host capabilities.

47

How does Environment-specific configuration work in ASP.NET Core?

ASP.NET Core detects environments using the ASPNETCORE_ENVIRONMENT environment variable (Development, Staging, Production).

Configuration providers load appsettings.json followed by appsettings.{Environment}.json to override values.

Environment variables and command-line arguments load last, taking the highest configuration precedence.

The IWebHostEnvironment interface allows code to conditionally execute based on IsDevelopment() checks.

Developers use User Secrets in development to avoid committing production connection strings to source control.

48

What is the Options Pattern and how do IOptions , IOptionsSnapshot , and IOptionsMonitor differ?

The Options Pattern uses strongly typed classes to represent configuration sections from appsettings.json.

IOptions is registered as a Singleton and reads configuration once at startup without detecting runtime changes.

IOptionsSnapshot is registered as Scoped and re-reads configuration on each new HTTP request for hot reloading.

IOptionsMonitor is registered as a Singleton that supports realtime change notifications via OnChange events.

Use IOptionsSnapshot in scoped web controllers and IOptionsMonitor in singleton background services.

49

How does Structured Logging work with ILogger in ASP.NET Core?

Structured logging captures message templates along with distinct key-value parameters rather than plain text strings.

Message templates preserve property data types for querying in log analyzers like Seq, Elasticsearch, or Application Insights.

ILogger provides standard log levels: Trace, Debug, Information, Warning, Error, and Critical.

Log enrichment libraries such as Serilog add contextual correlation IDs, machine names, and user identifiers.

Structured logs allow querying specific property values like UserId or OrderTotal across millions of log entries.

50

What are Health Checks in ASP.NET Core and how are they configured?

Health checks provide endpoints that report application, database, cache, and third-party service readiness.

Services register checks using builder.Services.AddHealthChecks() and expose them with app.MapHealthChecks(“/health”).

Checks return status states: Healthy, Degraded, or Unhealthy based on custom verification logic.

Liveness probes verify if the application process is running and restart unresponsive containers.

Readiness probes verify if dependencies like SQL Server and Redis are available before routing traffic.

Level 6

Dependency Injection & Configuration

10 Questions
51

What is Inversion of Control (IoC) and Dependency Injection (DI)?

Inversion of Control is an architectural principle where control of object creation and lifecycle is delegated to a framework.

Dependency Injection is a design pattern implementing IoC by passing dependencies into an object via constructors or methods.

Instead of classes instantiating their own concrete dependencies, an IoC container resolves and provides them.

DI decouples components, enforces the Single Responsibility Principle, and simplifies automated unit testing with mock implementations.

ASP.NET Core includes a built-in lightweight IoC container configured via IServiceCollection.

52

What are the three service lifetimes in ASP.NET Core DI?

Transient services are created every time they are requested from the service container.

Scoped services are created once per client HTTP request cycle and shared across that request.

Singleton services are created once on the first request and shared across the entire application lifetime.

Use Transient for lightweight stateless services, Scoped for stateful request workflows like DbContext, and Singleton for caches.

Register lifetimes using AddTransient, AddScoped, and AddSingleton on IServiceCollection.

53

What is a Captive Dependency and how can it cause severe bugs?

A captive dependency occurs when a service with a longer lifetime consumes a service with a shorter lifetime.

For example, a Singleton service injecting a Scoped service like DbContext captures that scoped instance permanently.

The captive scoped instance never gets disposed, leading to memory leaks, concurrency violations, and stale cached data.

DbContext is not thread-safe; concurrent requests accessing a captive DbContext encounter race conditions.

ASP.NET Core performs scope validation in the Development environment by default to detect captive dependencies on startup.

54

How do you resolve scoped services inside a BackgroundService or Singleton?

A Singleton cannot inject a Scoped service directly into its constructor due to captive dependency rules.

Instead, the Singleton injects IServiceProvider or IServiceScopeFactory into its constructor.

When scoped work needs execution, the service calls serviceProvider.CreateScope() within a using statement.

Dependencies are resolved from scope.ServiceProvider and properly disposed when the scope exits.

This pattern allows BackgroundService workers to safely use Entity Framework DbContext instances for background batch processing.

55

What is Keyed Services support introduced in .NET 8?

Keyed Services allow registering and resolving multiple implementations of the same service interface using unique keys.

Services are registered using AddKeyedSingleton, AddKeyedScoped, or AddKeyedTransient with a lookup key.

Consumers inject dependencies using the [FromKeyedServices(“keyName”)] attribute on constructor or action parameters.

This eliminates complex factory patterns previously required when selecting implementations dynamically based on context.

It is widely used for multi-tenant payment gateways, notification channels, and cloud storage providers.

56

What is the difference between ServiceProvider.GetService and GetRequiredService ?

GetService returns null if the requested service type is not registered in the IoC container.

GetRequiredService returns the registered instance or throws an InvalidOperationException if the service is missing.

Use GetRequiredService when a dependency is mandatory for the application component to function correctly.

Use GetService only when a dependency is genuinely optional and null is handled gracefully by fallback logic.

GetRequiredService helps fail fast during application startup and troubleshooting.

57

How do you implement custom Configuration Providers in .NET?

Custom configuration providers load settings from non-standard sources like custom databases, cloud vaults, or remote APIs.

A provider implements IConfigurationSource and inherits from the ConfigurationProvider base class.

The Load method fetches external data and populates the internal Data dictionary of key-value pairs.

Providers register into the configuration pipeline using builder.Configuration.Add(new CustomConfigurationSource()).

They support automatic polling or event-driven reloading when underlying configuration sources update.

58

How do you register multiple implementations of an interface in ASP.NET Core?

Registering multiple concrete types against the same interface appends each type to the internal descriptor list.

Injecting IEnumerable<IService> injects all registered implementations in the order they were registered.

Injecting the single interface IService directly resolves only the last registered implementation.

TryAddEnumerable from Microsoft.Extensions.DependencyInjection.Extensions prevents registering duplicate implementation types.

This pattern is ideal for validation pipelines, event notification handlers, and strategy pattern implementations.

59

What is Scrutor and why is assembly scanning useful in .NET DI?

Scrutor is a popular open-source NuGet library extending ASP.NET Core dependency injection capabilities.

It provides fluent assembly scanning to automatically discover and register classes matching specified conventions.

Instead of writing dozens of manual AddScoped lines, Scrutor registers all services ending in “Service” or “Repository”.

It also implements the Decorator pattern seamlessly, wrapping existing service registrations with cross-cutting concerns.

Assembly scanning reduces registration boilerplate and ensures newly created domain services are registered automatically.

60

How does IHttpClientFactory prevent socket exhaustion in .NET?

Instantiating HttpClient with the new keyword can exhaust available operating system network sockets under high load.

Even when disposed, underlying TCP sockets linger in the TIME_WAIT state for several minutes.

IHttpClientFactory manages the lifecycle of underlying HttpMessageHandler pools and reuses active socket connections.

It rotates handler pools periodically to respect DNS update changes while maintaining socket efficiency.

Named and typed clients configure base URLs, headers, and resilient Polly retry policies cleanly.

Level 7

Middleware Pipeline & Error Handling

10 Questions
61

How do you build custom Middleware in ASP.NET Core?

Custom middleware can be built using convention-based classes or factory-based classes implementing IMiddleware.

A convention-based middleware accepts RequestDelegate in its constructor to represent the next pipeline step.

It implements an asynchronous InvokeAsync method receiving the current HttpContext.

The middleware executes custom pre-processing logic, calls await _next(context), and executes post-processing logic.

Extension methods like app.UseCustomMiddleware() provide clean registration semantics in Program.cs.

62

What is the difference between IMiddleware and standard convention-based middleware?

Convention-based middleware is registered as a Singleton at application startup and cannot inject scoped services into its constructor.

Scoped dependencies must be injected directly into the InvokeAsync method signature on each request.

Factory-based middleware implements the IMiddleware interface and can be registered with Scoped lifetimes.

IMiddleware provides stronger compile-time type safety but requires explicit registration in the DI container.

Convention-based middleware remains the standard pattern across Microsoft framework components.

63

How does Exception Handling Middleware work in ASP.NET Core?

UseExceptionHandler registers a global exception handling middleware near the very beginning of the pipeline.

When an unhandled exception bubbles up from controllers or downstream middleware, it catches the exception.

It clears the corrupted response, logs the detailed diagnostic exception stack trace, and resets the pipeline.

It re-executes an error endpoint or writes a standardized RFC 7807 ProblemDetails JSON response to the client.

This prevents sensitive internal application stack traces from leaking to public API consumers.

64

What is IExceptionHandler introduced in .NET 8?

IExceptionHandler provides a centralized, modern interface for handling unhandled exceptions across web applications.

Classes implement the TryHandleAsync method to catch exceptions, format ProblemDetails, and write custom HTTP responses.

Multiple exception handlers can be chained in order of specificity to handle domain-specific errors differently.

Handlers return true if the exception was fully handled, or false to allow the next handler in the chain to execute.

It integrates with builder.Services.AddExceptionHandler<CustomHandler>() and app.UseExceptionHandler().

65

What is the RFC 7807 ProblemDetails specification and how does .NET support it?

ProblemDetails is an IETF industry standard defining machine-readable JSON error payloads for HTTP APIs.

Standard fields include type, title, status, detail, instance, and custom extension keys.

ASP.NET Core provides the built-in ProblemDetails class and Problem() controller helper methods.

builder.Services.AddProblemDetails() automatically transforms model validation and uncaught exceptions into standard ProblemDetails.

Using ProblemDetails standardizes client-side error parsing across web, mobile, and third-party API integrations.

66

How does Routing Middleware work internally in ASP.NET Core?

Routing matches incoming HTTP request paths to executable endpoints registered in the application.

EndpointRoutingMiddleware (UseRouting) analyzes the URL and selects the best matching endpoint using a route tree.

EndpointMiddleware (UseEndpoints) executes the selected endpoint delegate or controller action.

Splitting routing into two steps allows intermediate middleware like UseAuthentication and UseCors to inspect the matched endpoint metadata.

Attribute routing provides explicit URL templates directly on controller classes and action methods.

67

What is CORS and how is it properly configured in ASP.NET Core?

Cross-Origin Resource Sharing (CORS) is a browser security mechanism restricting cross-origin HTTP requests.

ASP.NET Core handles CORS preflight OPTIONS requests and injects Access-Control-Allow-* headers.

Policies are defined using builder.Services.AddCors() specifying allowed origins, HTTP methods, and headers.

app.UseCors(“PolicyName”) must be placed between UseRouting() and UseAuthentication() in the pipeline.

Wildcard AllowAnyOrigin() should never be combined with AllowCredentials() due to modern browser security restrictions.

68

How does Response Caching Middleware differ from Output Caching?

Response Caching relies on standard HTTP Cache-Control headers and is primarily interpreted by client browsers and upstream proxies.

Output Caching, introduced in .NET 8, provides rich server-side caching of generated HTTP responses.

Output Caching supports cache tagging, programmatic eviction by tag, cache locking, and Redis backing stores.

Output Caching caches content regardless of client Cache-Control request headers when configured on endpoints.

Use Output Caching on read-heavy API endpoints to dramatically reduce database load and server computation.

69

How does Rate Limiting Middleware work in .NET 7/8?

Built-in rate limiting middleware protects APIs from denial-of-service attacks, resource starvation, and brute-force abuse.

Algorithms include Fixed Window, Sliding Window, Token Bucket, and Concurrency Limiters.

Policies configure maximum request limits, replenishment intervals, queue limits, and client partition keys like IP address or user ID.

Registered using builder.Services.AddRateLimiter() and applied to endpoints using [EnableRateLimiting(“PolicyName”)].

Rejected requests automatically return HTTP 429 Too Many Requests with a Retry-After response header.

70

How do you implement Correlation IDs across the ASP.NET Core pipeline?

A Correlation ID is a unique GUID passed across distributed services to track an end-to-end user transaction in logs.

A custom correlation middleware checks for an incoming X-Correlation-ID header on HttpContext.Request.

If absent, the middleware generates a new GUID and attaches it to the request and response headers.

The ID is pushed onto the Serilog or ILogger LogContext using BeginScope for automatic inclusion in all downstream log messages.

Downstream HttpClient handlers forward the header to external microservices to maintain distributed tracing continuity.

Level 8

RESTful Web APIs & Routing

10 Questions
71

What does the [ ApiController ] attribute do in ASP.NET Core?

The [ApiController] attribute applies opinionated API conventions to controller classes.

It enforces automatic HTTP 400 responses with ProblemDetails when ModelState validation fails.

It automatically infers parameter binding sources like [FromBody] for complex objects and [FromRoute] for path parameters.

It requires attribute routing on all actions rather than relying on global conventional routes.

It automatically maps multipart/form-data requests for IFormFile parameters without manual binding code.

72

What are Minimal APIs and how do they compare to Controller-based APIs?

Minimal APIs define HTTP endpoints using concise lambda expressions directly on WebApplication without controller overhead.

They reduce boilerplate by eliminating controller classes, action attributes, and reflection-based controller discovery.

Minimal APIs compile with higher startup speed and deliver lower memory consumption and higher request throughput.

Controller-based APIs provide structured organization, action filter pipelines, and familiar conventions for large monolithic applications.

Minimal APIs are ideal for cloud-native microservices, serverless functions, and high-performance gateway proxies.

73

What is the difference between [ FromBody ], [ FromQuery ], [ FromRoute ], and [ FromHeader ]?

[FromBody] deserializes the incoming HTTP request body into a complex C# model using the configured JSON serializer.

[FromQuery] binds parameters from key-value query string values appended to the request URL after the question mark.

[FromRoute] binds parameters from matching URL route tokens defined in the route template.

[FromHeader] binds values from specified incoming HTTP request headers.

Explicit binding attributes clarify API contracts and resolve ambiguous parameter binding conflicts.

74

How does Content Negotiation work in ASP.NET Core Web API?

Content negotiation allows clients to request specific data representations using the Accept HTTP request header.

The server inspects the Accept header (such as application/json or application/xml) and matches it against registered OutputFormatters.

If a match is found, the corresponding formatter serializes the return object into the requested MIME type.

If no match is found, ASP.NET Core defaults to JSON or returns HTTP 406 Not Acceptable if ReturnHttpNotAcceptable is enabled.

Formatters are registered on controllers using builder.Services.AddControllers(options => options.OutputFormatters.Add(…)).

75

What are the best practices for RESTful API Status Codes?

Use 200 OK for successful GET/PUT/PATCH requests and 201 Created with a Location header for successful POST creations.

Use 204 No Content for successful operations returning no payload, such as DELETE requests.

Use 400 Bad Request for client validation failures and 401 Unauthorized for missing or invalid authentication credentials.

Use 403 Forbidden when an authenticated user lacks permission, and 404 Not Found for non-existent resources.

Use 409 Conflict for business state conflicts like duplicate emails, and 500 Internal Server Error for unhandled server crashes.

76

What is API Versioning and how is it implemented in ASP.NET Core?

API versioning allows evolving API schemas without breaking existing mobile and third-party client integrations.

Common strategies include URL path versioning (/api/v1/orders), query string versioning (?api-version=1.0), and header versioning.

The Asp.Versioning.Mvc library provides standard versioning support via builder.Services.AddApiVersioning().

Controllers and endpoints map to specific versions using attributes like [ApiVersion(“1.0”)] and [ApiVersion(“2.0”)].

URL path versioning remains the most widely adopted and transparent approach across industry public APIs.

77

How does Swagger / OpenAPI integration work in ASP.NET Core?

Swagger provides interactive documentation and client generation tools conforming to the OpenAPI specification.

Libraries like Swashbuckle and Microsoft.AspNetCore.OpenApi inspect endpoints, models, and attributes to generate swagger.json.

Swagger UI renders an interactive browser interface allowing developers to test API endpoints directly.

XML documentation comments on controllers and models can be included to populate endpoint descriptions and parameter summaries.

JWT authorization schemes can be configured in Swagger to enable Bearer token authentication testing in the browser.

78

What is the difference between IActionResult and ActionResult ?

IActionResult is an interface representing an HTTP action result like Ok(), NotFound(), or BadRequest().

ActionResult<T> is a wrapper type supporting either an IActionResult or a strongly typed return object T directly.

ActionResult<T> enables compile-time type safety while retaining the flexibility to return different HTTP status codes.

OpenAPI tools inspect ActionResult<T> to infer return payload schemas automatically without extra [ProducesResponseType] attributes.

ActionResult<T> is the recommended modern return type for all RESTful controller actions.

79

How do you implement File Uploads efficiently in ASP.NET Core?

Small files can be uploaded using IFormFile parameters, buffering incoming multipart form streams into memory or disk.

For large files exceeding hundreds of megabytes, buffered uploads cause high memory pressure and server throttling.

Streaming uploads read the raw multipart stream directly from HttpRequest.Body using MultipartReader.

Streaming processes chunks sequentially, saving bytes directly to disk or cloud storage without buffering the entire file in memory.

Disable request body size limits using [RequestSizeLimit] and disable form value model binding using custom filter attributes.

80

What are Route Constraints and when should they be used?

Route constraints validate that URL route parameters match expected data types and formats before invoking action methods.

Syntax includes inline constraints like {id:int}, {slug:alpha}, {date:datetime}, and {guid:guid}.

Regex constraints like {code:regex(^\d{{3}}$)} validate custom string formats.

If an incoming URL parameter fails the constraint, the route engine treats it as a non-match and returns HTTP 404.

Route constraints disambiguate overloaded routes but should not replace comprehensive business model validation.

Level 9

Model Binding, Validation & Filters

10 Questions
81

How does Model Binding work internally in ASP.NET Core?

Model binding maps incoming HTTP request data from route values, query strings, headers, and bodies to C# action parameters.

IModelBinderProvider instances scan registered binders to select the appropriate binder for each parameter type.

Value providers extract raw string values from request components in a predefined sequence.

The binder parses strings into target .NET data types, handling conversions, complex object graphs, and collections.

Any type conversion errors or parsing failures record validation errors onto the Controller’s ModelState dictionary.

82

What is the ASP.NET Core Filter Pipeline and its execution order?

Filters run within the ASP.NET Core action invocation pipeline to execute cross-cutting concerns around action methods.

The five filter stages execute in order: Authorization Filters, Resource Filters, Action Filters, Exception Filters, and Result Filters.

Authorization filters determine whether the user is authorized to execute the request.

Resource filters wrap model binding, execution, and result formatting, making them ideal for performance caching.

Action filters wrap individual action method execution, inspecting arguments and return values.

83

What is the difference between Middleware and Action Filters?

Middleware executes in the lower-level HTTP pipeline with access only to raw HttpContext before routing completes.

Filters execute inside the MVC routing pipeline with access to ActionExecutingContext, ActionDescriptor, and ModelState.

Middleware is ideal for global concerns like authentication, CORS, compression, and request logging.

Filters are ideal for MVC concerns like model validation, action authorization, response wrapping, and action execution auditing.

Middleware applies to all endpoints, whereas filters can be scoped globally, per controller, or per action method.

84

What is FluentValidation and why is it preferred over Data Annotations?

Data Annotations apply validation rules using attributes directly on model class properties.

FluentValidation separates validation logic from model entities into dedicated validator classes inheriting AbstractValidator<T>.

FluentValidation provides rich, fluent syntax for complex cross-property validation, conditional rules, and asynchronous database checks.

Separating validation enforces the Single Responsibility Principle and keeps domain models clean of UI validation annotations.

It integrates seamlessly into ASP.NET Core via Dependency Injection and automatically populates ModelState errors.

85

How do you implement custom Action Filters?

Custom action filters inherit from ActionFilterAttribute or implement IActionFilter or IAsyncActionFilter.

IAsyncActionFilter defines the OnActionExecutionAsync method receiving ActionExecutingContext and ActionExecutionDelegate.

Code before await next() inspects or modifies incoming action arguments via context.ActionArguments.

Setting context.Result short-circuits the pipeline and returns an immediate response without invoking the action.

Code after await next() inspects and modifies the returned ActionExecutedContext result before it renders.

86

What is the difference between synchronous and asynchronous filters?

Synchronous filters implement pairs of methods like OnActionExecuting and OnActionExecuted.

Asynchronous filters implement a single method like OnActionExecutionAsync using an awaitable next delegate.

If both synchronous and asynchronous interfaces are implemented on the same filter class, the runtime calls only the async method.

Async filters provide cleaner resource management, cancellation token forwarding, and prevent thread blocking.

Modern ASP.NET Core applications should exclusively implement asynchronous filter interfaces.

87

What are TypeFilter and ServiceFilter attributes used for?

Standard filter attributes cannot inject dependencies into their constructors because attributes require compile-time constants.

ServiceFilter resolves the filter instance directly from the Dependency Injection container at runtime.

The filter class must be explicitly registered as a service in builder.Services before using [ServiceFilter(typeof(MyFilter))].

TypeFilter instantiates the filter using type activation (ActivatorUtilities), resolving constructor parameters from DI automatically.

TypeFilter does not require pre-registering the filter class in the service collection.

88

How does IAsyncAuthorizationFilter work?

IAsyncAuthorizationFilter runs first in the filter pipeline to verify user permissions before model binding occurs.

It defines OnAuthorizationAsync receiving AuthorizationFilterContext.

If authorization fails, the filter sets context.Result to UnauthorizedResult (401) or ForbidResult (403).

Setting context.Result immediately short-circuits execution, preventing unnecessary model binding and database queries.

Custom authorization filters should complement, rather than replace, standard ASP.NET Core Policy-based authorization.

89

What are Result Filters and when should they be used?

Result filters surround the execution of the action result, running after the action method returns successfully.

They implement IAsyncResultFilter or IResultFilter, defining OnResultExecutionAsync.

Result filters can modify, wrap, or transform the action result before it serializes to the client response stream.

They are commonly used to inject custom HTTP response headers or wrap return objects in standardized API response envelopes.

Result filters only execute if the action method completed without throwing unhandled exceptions.

90

How do you handle Model Validation automatically in Minimal APIs?

Minimal APIs do not use the MVC controller filter pipeline and do not automatically validate Data Annotations by default.

In modern .NET, Endpoint Filters (AddEndpointFilter) intercept Minimal API invocations to validate parameters.

An endpoint filter resolves the appropriate IValidator<T> from DI, invokes ValidateAsync, and returns Results.ValidationProblem on failure.

Libraries like FluentValidation provide extension methods that automatically register validation filters on endpoint route groups.

This ensures Minimal APIs maintain robust, automated validation pipelines identical to traditional controllers.

Level 10

Entity Framework Core Fundamentals

10 Questions
91

What is Entity Framework Core and how does DbContext work?

Entity Framework Core is a lightweight, extensible, cross-platform Object-Relational Mapper (ORM) for .NET.

DbContext acts as the central bridge between domain entity classes and database tables.

It manages database connections, configures model schemas, handles transactions, and persists changes.

DbSet<TEntity> properties represent database tables that can be queried and mutated using LINQ.

DbContext instances are registered with Scoped lifetimes in ASP.NET Core to ensure one context per HTTP request.

92

What are EF Core Migrations and how do they work?

Migrations provide a structured way to evolve relational database schemas in sync with C# domain model changes.

When models change, dotnet ef migrations add generates C# migration files describing Up and Down schema modifications.

The Up method applies changes like creating tables or adding columns, while Down reverts them.

dotnet ef database update executes pending migrations against the target database engine.

EF Core tracks applied migrations in a special database table named __EFMigrationsHistory.

93

What is the difference between Fluent API and Data Annotations in EF Core?

Data Annotations apply configuration attributes like [Required], [MaxLength], and [ForeignKey] directly to entity properties.

Fluent API configures entity mappings programmatically inside the DbContext.OnModelCreating method using ModelBuilder.

Fluent API keeps domain entity classes clean of database-specific persistence concerns.

Fluent API provides superior flexibility, supporting advanced features like composite primary keys, shadow properties, and table splitting.

When conflicts occur, configurations defined in Fluent API override Data Annotations.

94

What are the Entity States in the EF Core Change Tracker?

The Change Tracker monitors entity modifications to construct accurate SQL INSERT, UPDATE, and DELETE statements.

The five entity states are: Added, Unchanged, Modified, Deleted, and Detached.

Added entities generate SQL INSERT statements upon calling SaveChanges.

Modified entities track property changes to generate optimized SQL UPDATE statements updating only modified columns.

Deleted entities generate SQL DELETE statements, while Detached entities are not tracked by the context.

95

What is the difference between Eager Loading, Lazy Loading, and Explicit Loading?

Eager loading loads related entities as part of the initial database query using the Include and ThenInclude methods.

Lazy loading defers loading related entities until their navigation properties are accessed in code, requiring virtual properties and proxies.

Explicit loading manually queries related entities for a tracked parent entity using Entry(parent).Collection(…).Load().

Lazy loading often causes hidden N+1 performance problems in web applications and is generally discouraged in production APIs.

Eager loading remains the standard, high-performance approach for building explicit API response models.

96

What is the N+1 Query Problem in EF Core and how do you fix it?

The N+1 query problem occurs when an application executes 1 initial query to fetch N parent records, then N subsequent queries for children.

For example, fetching 100 orders and looping through them to access order items triggers 101 separate database roundtrips.

This dramatically degrades network throughput and database CPU performance under production workloads.

Fix it by using eager loading with .Include(o => o.OrderItems) to fetch all required data in a single joined SQL query.

Alternatively, use projection with .Select() to retrieve only the required child fields in one optimized query.

97

What is AsNoTracking () and when should it be used?

AsNoTracking() instructs the Change Tracker not to track entity instances returned by a LINQ query.

Skipping change tracking eliminates memory overhead, identity resolution lookups, and snapshot generation.

Queries execute significantly faster and consume substantially less server memory.

Always use AsNoTracking() for read-only GET endpoints where retrieved entities will not be mutated and saved back to the database.

DbContext.ChangeTracker.QueryTrackingBehavior can also configure no-tracking globally across the context.

98

How does EF Core handle Database Concurrency Conflicts?

EF Core uses Optimistic Concurrency to detect whether another user modified a row between reading and saving it.

A concurrency token property or row version column is configured using the [Timestamp] attribute or IsRowVersion() in Fluent API.

SQL UPDATE statements include the concurrency token in their WHERE clause alongside the primary key.

If the row was modified concurrently, zero rows are updated, causing EF Core to throw a DbUpdateConcurrencyException.

Applications catch this exception to resolve conflicts by reloading latest data, merging values, or prompting the user.

99

What are Global Query Filters in EF Core?

Global query filters are LINQ filter expressions applied automatically to all queries executed against an entity type.

They are configured inside OnModelCreating using builder.Entity<T>().HasQueryFilter(e => !e.IsDeleted).

They are commonly used to implement automated Soft Delete and Multi-Tenant data isolation.

Queries automatically append the filter to SQL WHERE clauses without requiring developers to write them manually.

The filter can be bypassed for administrative queries using the IgnoreQueryFilters() method.

100

How do you execute Raw SQL Queries safely in EF Core?

Raw SQL is executed using FromSqlRaw or FromSqlInterpolated on DbSet<TEntity> to map results back to entity types.

FromSqlInterpolated uses C# string interpolation to automatically parameterize inputs, preventing SQL injection vulnerabilities.

Non-entity queries returning custom DTOs can use Database.SqlQuery<T>() in modern EF Core.

Executing arbitrary commands without return values uses Database.ExecuteSqlInterpolatedAsync().

Always use parameterized SQL queries and never concatenate unvalidated user strings into raw SQL command text.

Level 11

Advanced EF Core & Query Optimization

10 Questions
101

What is Query Splitting in EF Core and why is it important?

When eager loading multiple one-to-many collections with Include, EF Core by default generates a single SQL query using multiple LEFT JOINs.

This causes a Cartesian explosion of rows returned from the database, transmitting massive duplicate column data across the network.

Query Splitting instructs EF Core to generate multiple smaller SQL queries, one for each included collection, using AsSplitQuery().

It eliminates Cartesian multiplication and significantly reduces database network transfer and memory overhead.

Query splitting can be configured per-query or configured globally as the default behavior on the DbContext options.

102

What are Shadow Properties and Backing Fields in EF Core?

Shadow properties are properties that exist in the EF Core entity model and database schema but are not defined in the C# entity class.

They are configured via Fluent API using entityBuilder.Property<DateTime>(“LastModified”) and accessed using EF.Property<T>(entity, “name”).

They are ideal for cross-cutting audit metadata like CreatedAt, CreatedBy, and row timestamps that domain logic does not need to expose.

Backing fields allow EF Core to read and write database values directly to private fields rather than public property getters and setters.

This enables encapsulation in Domain-Driven Design (DDD) where public properties expose only read-only getters.

103

How do you implement the Interceptor Pattern in EF Core?

Interceptors allow capturing, modifying, or suppressing database operations executed by EF Core before and after they occur.

Classes inherit from interfaces like DbCommandInterceptor, SaveChangesInterceptor, or TransactionInterceptor.

A SaveChangesInterceptor can automatically detect Added or Modified entities and populate audit fields like UpdatedAt and UpdatedBy.

Command interceptors can inspect generated SQL, inject custom logging, enforce query timeouts, or simulate query failures during testing.

Interceptors are registered on DbContextOptionsBuilder using the AddInterceptors method.

104

What is DbContext Pooling and how does it improve performance?

Instantiating a new DbContext instance on every incoming HTTP request involves allocating memory and initializing internal service state.

DbContext pooling maintains a warm pool of initialized DbContext instances ready for immediate reuse.

When an HTTP request finishes, EF Core resets the DbContext state and returns it to the pool instead of discarding it to the GC.

Registered using builder.Services.AddDbContextPool<MyDbContext>() instead of AddDbContext().

Pooling reduces GC allocation pressure and can boost request throughput by up to 20% in high-load web APIs.

105

How do you perform Bulk Operations (Bulk Update / Bulk Delete) in modern EF Core?

Historically, updating or deleting 10,000 records required loading all 10,000 entities into memory, modifying them, and calling SaveChanges.

This generated 10,000 individual SQL UPDATE or DELETE statements, causing severe performance bottlenecks.

Modern EF Core provides ExecuteUpdateAsync and ExecuteDeleteAsync to perform bulk operations directly in the database in a single roundtrip.

Syntax: dbContext.Orders.Where(o => o.Status == “Expired”).ExecuteDeleteAsync().

These methods execute directly against the database without loading entities into memory or engaging the Change Tracker.

106

What is the difference between Client Evaluation and Server Evaluation in EF Core?

Server evaluation translates LINQ operators into SQL commands executed directly by the database server.

Client evaluation executes C# logic in server application memory on rows already retrieved from the database.

If a LINQ expression contains custom C# methods that the EF provider cannot translate to SQL, EF Core throws an InvalidOperationException.

In older EF versions, client evaluation happened silently, accidentally downloading entire tables into server memory.

Always ensure WHERE filtering and aggregations evaluate on the database server before materializing with ToListAsync.

107

What are Value Conversions in EF Core?

Value converters allow mapping property types in C# classes to different data types in the relational database.

For example, a strongly typed C# enum can be stored as a human-readable string in the database column instead of an integer.

Complex objects or arrays can be serialized and stored as JSON strings in a single database column using a value converter.

They are configured in Fluent API using entityBuilder.Property(e => e.Status).HasConversion<string>().

Modern EF Core also provides rich support for complex type JSON columns using OwnsOne and ToJson.

108

What are Table per Hierarchy (TPH) vs Table per Type (TPT) in EF Core inheritance?

Table per Hierarchy (TPH) maps an entire class inheritance hierarchy into a single database table using a discriminator column.

TPH is the default EF Core mapping because it delivers high performance and avoids multi-table SQL joins.

Table per Type (TPT) maps each derived class in the hierarchy to its own distinct database table containing only subclass properties.

TPT requires SQL JOINs across base and derived tables, resulting in slower query performance for polymorphic queries.

TPH remains the recommended approach for most domain hierarchies unless strict database normalization constraints require TPT.

109

How does Compiled Query caching work in EF Core?

Every time a LINQ query executes, EF Core checks an internal query cache to avoid re-translating the LINQ expression tree to SQL.

EF Core parameterizes constants automatically so subsequent query executions reuse the cached relational command tree.

For ultra-high-throughput code paths, EF.CompileAsyncQuery compiles the LINQ query into an immutable, reusable delegate.

Invoking the compiled delegate bypasses expression tree inspection entirely, reducing query execution overhead to near-zero.

This is particularly beneficial for high-frequency queries like looking up users by ID in authentication endpoints.

110

How do you manage Database Transactions with IDbContextTransaction ?

By default, SaveChangesAsync automatically wraps all database modifications within a single atomic database transaction.

When coordinating multiple SaveChanges calls or combining EF Core operations with Dapper, an explicit transaction is required.

Call await dbContext.Database.BeginTransactionAsync() to initiate an explicit IDbContextTransaction.

Execute business updates, call SaveChangesAsync on each step, and conclude with await transaction.CommitAsync().

If any exception occurs, the catch block calls await transaction.RollbackAsync() to ensure atomic data integrity.

Level 12

SQL Server & Relational Database Engineering

10 Questions
111

What is the difference between Clustered and Non-Clustered Indexes in SQL Server?

A clustered index determines the physical storage order of data rows on disk; a table can have only one clustered index.

The leaf nodes of a clustered index contain the actual physical table data pages.

A non-clustered index is a separate B-tree structure holding index keys and row locators (pointers) pointing to the actual data.

A table can have hundreds of non-clustered indexes to accelerate search filtering across multiple columns.

Primary keys default to clustered indexes unless explicitly created as non-clustered.

112

What is an Index Seek vs Index Scan in SQL Server execution plans?

An Index Seek traverses the B-tree structure directly to locate specific qualifying rows with high efficiency.

An Index Scan reads all pages in the entire index from start to finish, examining every row sequentially.

Index Seeks are significantly faster and consume minimal I/O compared to full Index Scans.

An Index Scan occurs when no index covers the filter criteria or when predicates use non-sargable functions like LOWER(column).

Query tuning aims to turn expensive Index Scans into efficient Index Seeks on high-cardinality columns.

113

What is a Covering Index and why are INCLUDED columns useful?

A covering index is a non-clustered index containing all columns referenced in the SELECT, WHERE, and JOIN clauses of a query.

When an index is covering, the SQL query optimizer satisfies the entire request directly from the index without reading the table.

This eliminates expensive Key Lookups or RID Lookups into the clustered index pages.

The INCLUDE clause appends non-key columns to the leaf level of the index without expanding the intermediate B-tree size.

This keeps index maintenance lightweight while delivering maximum query performance.

114

What are SARGable queries and how do non-sargable predicates hurt performance?

SARGable stands for Search Argument Able, meaning the query engine can use an index seek to filter data.

Applying functions to indexed columns in WHERE clauses, such as WHERE YEAR(OrderDate) = 2026, ruins sargability.

When a function wraps a column, SQL Server must compute the function for every single row, forcing a full index scan.

Rewrite predicates to isolate the column: WHERE OrderDate >= ‘2026-01-01’ AND OrderDate < ‘2027-01-01’.

Similarly, leading wildcard LIKE queries like ‘%term’ prevent index seeks, whereas ‘term%’ remains fully sargable.

115

What are the four ACID properties in relational database systems?

Atomicity guarantees that all operations in a transaction succeed completely or roll back entirely with no partial state.

Consistency ensures a transaction transitions the database from one valid state to another, enforcing all schema constraints.

Isolation ensures concurrent transactions execute without seeing intermediate, uncommitted changes from other transactions.

Durability guarantees that once a transaction commits, its data changes survive permanently, even during power failures or server crashes.

Relational engines enforce ACID using write-ahead transaction logging (WAL) and memory buffer pools.

116

What are Transaction Isolation Levels in SQL Server?

Read Uncommitted allows reading uncommitted data, introducing Dirty Reads, but offers the highest throughput.

Read Committed prevents dirty reads by acquiring shared locks during reads, but permits Non-Repeatable Reads.

Repeatable Read holds shared locks until the transaction completes, preventing non-repeatable reads but permitting Phantom Reads.

Serializable provides strict isolation using range locks, eliminating phantoms at the cost of high locking contention.

Snapshot Isolation uses row versioning in tempdb, allowing non-blocking reads while providing repeatable snapshot consistency.

117

What causes Database Deadlocks and how can you minimize them?

A deadlock occurs when two transactions hold locks on resources the other transaction needs to proceed, creating a cycle.

SQL Server automatically detects deadlocks, selects one transaction as the deadlock victim, and terminates it with error 1205.

Deadlocks are minimized by accessing database tables in the exact same sequential order across all application transactions.

Keep transactions as short as possible, avoiding long-running external API calls while holding open database transactions.

Use appropriate indexing to reduce lock footprints, and consider Read Committed Snapshot Isolation (RCSI) to stop readers blocking writers.

118

What is the difference between INNER JOIN , LEFT JOIN , FULL OUTER JOIN , and CROSS JOIN ?

INNER JOIN returns only the rows that have matching values in both joined tables.

LEFT JOIN returns all rows from the left table alongside matching rows from the right table, filling non-matches with NULL.

FULL OUTER JOIN returns all rows when there is a match in either the left or right table, returning NULLs for missing sides.

CROSS JOIN produces the Cartesian product, pairing every row in the first table with every row in the second table.

Ensure join predicates match indexed columns to prevent expensive nested loop scans and hash join memory spillage.

119

What is the difference between Stored Procedures, Views, and User-Defined Functions?

A Stored Procedure contains precompiled procedural T-SQL logic, accepts parameters, performs DDL/DML, and returns datasets.

A View is a stored virtual query table that simplifies complex joins and secures sensitive column access without storing data.

A User-Defined Function (UDF) computes and returns a scalar value or table, but cannot modify database state via INSERT or UPDATE.

Scalar UDFs can hurt performance when evaluated per-row in query projections due to iterative row-by-row execution.

Stored procedures provide fine-grained execution security and network traffic reduction for enterprise transaction workflows.

120

How does Database Index Fragmentation occur and how do you resolve it?

Index fragmentation occurs when data modifications (INSERTs, UPDATEs, and page splits) cause logical index pages to become out of order.

External fragmentation scatters logical index pages physically across disk; internal fragmentation leaves excessive free space on pages.

Fragmentation increases I/O overhead and reduces query cache efficiency during index scans.

Indexes with fragmentation between 5% and 30% are reorganized using ALTER INDEX REORGANIZE, defragmenting leaf pages online.

Indexes with fragmentation exceeding 30% are rebuilt using ALTER INDEX REBUILD, creating fresh contiguous B-tree pages.

Level 13

Dapper & High-Performance Data Access

10 Questions
121

What is Dapper and how does it compare to Entity Framework Core?

Dapper is a high-performance micro-ORM developed by Stack Overflow that extends the standard IDbConnection interface.

Unlike EF Core, Dapper does not generate SQL, manage change tracking, or handle migration schemas.

Developers write raw, optimized SQL queries and Dapper maps the returned database tabular results to C# objects with near-native ADO.NET speed.

EF Core provides developer productivity, change tracking, and LINQ abstraction for complex domain operations.

Dapper is ideal for high-throughput reporting, read-heavy query APIs, and complex stored procedure integration.

122

How does Dapper achieve near-native ADO.NET performance?

Dapper uses dynamic Intermediate Language (IL) generation and emit caching to map database columns to object properties.

When a query executes for the first time, Dapper analyzes the reader schema and generates specialized IL deserialization delegates.

These generated delegates are cached in memory, eliminating runtime reflection overhead on all subsequent query executions.

Dapper avoids tracking overhead, snapshot comparisons, and entity relationship validation entirely.

This makes Dapper‘s execution speed and memory allocations virtually identical to hand-tuned ADO.NET DataReader code.

123

How does Dapper prevent SQL Injection attacks?

Dapper prevents SQL injection by leveraging database command parameterization through anonymous parameter objects.

When passing parameters: connection.QueryAsync<User>(“SELECT * FROM Users WHERE Email = @Email”, new { Email = userEmail }).

Dapper maps anonymous object properties into proper DbParameter objects on the underlying database command.

User inputs are treated strictly as data literals by the database query engine, never as executable SQL commands.

Developers must never concatenate unsanitized user strings into the SQL text string passed to Dapper.

124

How do you execute One-to-Many relationship queries in Dapper ?

Dapper supports multi-mapping using the QueryAsync method with generic type parameters and a mapping delegate function.

Example: connection.QueryAsync<Order, OrderItem, Order>(sql, (order, item) => { order.Items.Add(item); return order; }, splitOn: “ItemId”).

The splitOn parameter tells Dapper where the columns of the first entity end and the columns of the child entity begin.

A local dictionary is maintained inside the mapping delegate to group child records under their corresponding parent entity instance.

This maps complex parent-child object graphs from a single joined SQL query result.

125

What is Dapper Multi-Query (QueryMultiple) and when should you use it?

QueryMultipleAsync executes a SQL script containing multiple distinct SELECT statements in a single database roundtrip.

The returned GridReader allows reading each result set sequentially using ReadAsync<T>().

Example: retrieving a customer profile, their recent orders, and notification settings all in one roundtrip.

Batching multiple queries into a single connection roundtrip minimizes network latency overhead significantly.

Always dispose the GridReader within a using statement to ensure underlying readers and connections close properly.

126

How do you handle Stored Procedures and Output Parameters in Dapper ?

Stored procedures are executed by setting CommandType.StoredProcedure on Dapper query and execution methods.

DynamicParameters allows adding input, output, and return value parameters with explicit database data types.

Example: parameters.Add(“@UserId”, dbType: DbType.Int32, direction: ParameterDirection.Output).

After calling connection.ExecuteAsync(“sp_CreateUser”, parameters, commandType: CommandType.StoredProcedure),

the output value is retrieved using parameters.Get<int>(“@UserId”).

127

What is the Hybrid EF Core + Dapper architecture pattern?

The hybrid pattern combines the strengths of both ORMs within the same application architecture.

EF Core is used for write operations (Command side), taking advantage of Change Tracking, domain validation, and SaveChanges.

Dapper is used for read operations (Query side), executing lightning-fast, hand-tuned SQL projections directly into DTOs.

Both ORMs share the same underlying database connection and transaction managed by dbContext.Database.GetDbConnection().

This architectural synergy is popular in high-performance CQRS and clean architecture enterprise applications.

128

How does Dapper handle buffered vs unbuffered queries?

By default, Dapper buffers query results, reading all rows into memory and returning a populated List<T>.

Setting buffered: false returns an unbuffered IEnumerable<T> that yields rows lazily as the consumer enumerates them.

Unbuffered queries keep the database connection and DataReader open during enumeration, requiring sequential reading.

Use buffered queries for small and medium datasets that need to be closed quickly to free database connections.

Use unbuffered queries for streaming millions of rows to a CSV export or file stream without consuming gigabytes of server RAM.

129

How do you implement custom Type Handlers in Dapper ?

Custom type handlers allow Dapper to serialize and deserialize custom domain types and non-standard column data.

A class inherits from SqlMapper.TypeHandler<T> and implements SetValue and Parse methods.

For example, a JsonTypeHandler can serialize complex C# objects into JSON strings for storage and parse them back.

Handlers are registered globally at application startup using SqlMapper.AddTypeHandler(new CustomHandler()).

This ensures Dapper maps custom value objects and strongly typed IDs seamlessly across all database interactions.

130

How do you manage connection lifecycles properly when using Dapper ?

Dapper requires an open IDbConnection instance, typically resolved via Dependency Injection as a Scoped service.

Connections should always be managed within using or await using statements to guarantee deterministic disposal.

If a connection is closed when a Dapper method is called, Dapper opens it automatically and closes it upon query completion.

Avoid opening connections prematurely before non-database operations to prevent holding pool connections idle.

Never share an IDbConnection instance across concurrent threads, as ADO.NET connections are strictly not thread-safe.

Level 14

Authentication, Identity & JWT

10 Questions
131

What is the difference between Authentication and Authorization?

Authentication is the process of verifying who a user is by validating their credentials like username and password.

Authorization is the process of verifying what an authenticated user has permission to do within the application.

Authentication always precedes authorization in the security pipeline.

Authentication issues an identity containing claims (such as UserId, Email, and Roles).

Authorization inspects those claims against application access policies before allowing request execution.

132

What is ASP.NET Core Identity and what features does it provide?

ASP.NET Core Identity is a comprehensive membership system for managing users, passwords, roles, and security tokens.

It provides out-of-the-box user registration, password hashing, two-factor authentication (2FA), and account confirmation.

It manages security stamps to invalidate active authentication cookies when passwords or security settings change.

It integrates with Entity Framework Core to persist user and role data into relational database schemas.

Services are registered using builder.Services.AddIdentity<ApplicationUser, IdentityRole>() and configured via IdentityOptions.

133

How does JSON Web Token (JWT) Authentication work in ASP.NET Core?

A JWT is a compact, URL-safe token consisting of three Base64URL-encoded parts: Header, Payload, and Signature.

Upon successful login, the server signs a JWT containing user claims using a secret key and returns it to the client.

Clients attach the token to subsequent requests inside the HTTP Authorization header as: Bearer <token>.

The JwtBearer middleware validates the signature, issuer, audience, and expiration date without querying the database.

If valid, it extracts the payload claims and populates the HttpContext.User ClaimsPrincipal automatically.

134

What is the difference between an Access Token and a Refresh Token?

An access token is a short-lived token (e.g., 15 minutes) used to authenticate API requests directly.

A refresh token is a long-lived, opaque token stored securely in the database and issued alongside the access token.

When the access token expires, the client sends the refresh token to a token refresh endpoint to obtain a new access token.

Using short-lived access tokens minimizes the exposure window if a token is intercepted or leaked.

Refresh tokens can be revoked or rotated in the database immediately if an account is compromised.

135

How do you implement Refresh Token Rotation and Revocation?

Refresh token rotation issues a brand new refresh token every single time an access token is refreshed.

The previous refresh token is immediately invalidated in the database, preventing token reuse.

If an attacker attempts to reuse an old, rotated refresh token, the server detects potential token theft.

Upon detecting reuse, the server revokes the entire family of refresh tokens, forcing the legitimate user to re-authenticate.

Refresh tokens should be stored in HTTP-only, secure, SameSite cookies to protect against client-side XSS theft.

136

What are the key parameters in TokenValidationParameters for JWT?

TokenValidationParameters configures the security validation rules applied by the JwtBearer authentication handler.

ValidateIssuer verifies that the token was issued by the trusted authority (ValidIssuer).

ValidateAudience verifies that the token was intended for this specific API resource (ValidAudience).

ValidateIssuerSigningKey validates the cryptographic signature using the shared symmetric or asymmetric public key.

ValidateLifetime verifies that the current timestamp is within the NotBefore and Expires validity window.

ClockSkew configures grace-period tolerance for server time drift and should be set to TimeSpan.Zero for strict expiration.

137

What is ClaimsPrincipal and how are user claims accessed?

ClaimsPrincipal represents the current user identity in ASP.NET Core, accessible via HttpContext.User.

A ClaimsPrincipal can contain one or more ClaimsIdentity instances, each holding a collection of Claim objects.

A Claim is a key-value statement about the user, such as NameIdentifier, Email, Role, or Department.

Code accesses claims using User.FindFirstValue(ClaimTypes.NameIdentifier) or User.HasClaim(type, value).

Claims represent verifiable statements certified by the authentication issuer for authorization decisions.

138

How do you secure Passwords properly in .NET?

Passwords must never be stored in plain text or using obsolete cryptographic hash algorithms like MD5 or SHA-1.

ASP.NET Core Identity uses PasswordHasher<T>, which implements PBKDF2 with HMAC-SHA256 and per-user cryptographic salts.

A unique random salt is generated for each password to protect against rainbow table dictionary attacks.

Key stretching with thousands of computation iterations slows down brute-force hardware cracking attacks.

Alternatively, modern applications leverage battle-tested algorithms like BCrypt or Argon2 for maximum password security.

139

What is External Authentication (OAuth 2.0 / OpenID Connect)?

External authentication delegates user login to identity providers like Google, Microsoft, GitHub, or Okta.

The user authenticates on the external provider’s trusted login portal rather than submitting passwords to the application.

OpenID Connect (OIDC) builds on OAuth 2.0 to provide standardized identity tokens (id_token) and profile information.

ASP.NET Core supports external providers via AddAuthentication().AddGoogle(), AddMicrosoftAccount(), or AddOpenIdConnect().

This eliminates the burden of storing passwords locally while enabling single sign-on (SSO) across enterprise applications.

140

How do you implement Two-Factor Authentication (2FA) in ASP.NET Core?

Two-Factor Authentication requires two distinct authentication factors: something you know (password) and something you have (device).

ASP.NET Core Identity supports Time-Based One-Time Passwords (TOTP) compatible with authenticator apps like Google Authenticator.

The server generates an unshared secret key, displays it to the user as a QR code, and verifies the 6-digit code.

The authenticator app derives time-synchronized 6-digit codes every 30 seconds using HMAC algorithms.

Recovery codes are generated and securely stored so users can regain access if their authenticator device is lost.

Level 15

Authorization, Claims & Policies

10 Questions
141

What is the difference between Role-Based, Claims-Based, and Policy-Based Authorization?

Role-based authorization checks whether a user belongs to specific named groups: [Authorize(Roles = “Admin,Manager”)].

Claims-based authorization checks for the presence of specific user attributes and values: User.HasClaim(“Department”, “HR”).

Policy-based authorization decouples authorization requirements from controller logic using rich, reusable rules.

Policies combine requirements, roles, claims, and context evaluations into named rules registered at startup.

Policy-based authorization is the recommended, highly extensible modern standard across ASP.NET Core.

142

How do you create and register a Policy-based Authorization rule?

Policies are registered inside builder.Services.AddAuthorization() using the AddPolicy method.

Example: options.AddPolicy(“RequireManagerOnly”, policy => policy.RequireRole(“Manager”).RequireClaim(“Level”, “Senior”)).

Policies are applied to controllers or endpoints using the [Authorize(Policy = “RequireManagerOnly”)] attribute.

Minimal APIs apply policies fluently using app.MapGet(“/data”, …).RequireAuthorization(“RequireManagerOnly”).

Centralizing authorization logic into named policies simplifies security auditing and policy evolution.

143

How do you implement custom Authorization Requirements and Handlers?

A custom requirement is a class implementing the IAuthorizationRequirement marker interface, defining requirement parameters.

A custom handler inherits from AuthorizationHandler<TRequirement>, implementing HandleRequirementAsync.

The handler inspects context.User claims, evaluates business rules, and calls context.Succeed(requirement) on success.

Handlers are registered as services in the Dependency Injection container (AddSingleton or AddScoped).

Multiple handlers can evaluate the same requirement, enabling flexible fallback or composite permission rules.

144

What is Resource-Based Authorization and when is it required?

Resource-based authorization evaluates permissions where access depends on the specific resource being requested.

For example, any author can edit documents, but an author can only edit documents that they personally created.

Because the resource must be retrieved from the database before checking ownership, attribute filters cannot perform this check.

The application injects IAuthorizationService and calls await authorizationService.AuthorizeAsync(User, document, “EditPolicy”).

If the check fails, the controller returns a ForbidResult (HTTP 403) to prevent unauthorized resource mutation.

145

How does View-Based / Conditional Authorization work?

Conditional authorization hides UI elements, action buttons, or navigation menus based on user permissions.

In Razor Views and Blazor components, developers inject IAuthorizationService directly into the presentation template.

Code checks: if ((await AuthorizationService.AuthorizeAsync(User, “AdminOnly”)).Succeeded) { <button>Delete</button> }.

In Blazor, the <AuthorizeView Policy=”AdminOnly”> component renders Authorized and NotAuthorized fragments conditionally.

UI hiding enhances user experience but must always be backed by server-side authorization on the API endpoints.

146

What is the difference between HTTP 401 Unauthorized and HTTP 403 Forbidden?

HTTP 401 Unauthorized means authentication is missing or invalid; the user’s identity is unknown to the server.

The client should authenticate with valid credentials before retrying the request.

HTTP 403 Forbidden means authentication succeeded, but the authenticated user lacks permission to access the resource.

Re-submitting the same credentials will not change the outcome; the user is simply not authorized.

ASP.NET Core returns ChallengeResult for 401 and ForbidResult for 403.

147

What does the [ AllowAnonymous ] attribute do and how does it work?

The [AllowAnonymous] attribute bypasses authorization checks for specific actions inside an [Authorize] controller.

For example, an AccountController decorated with [Authorize] can expose Login and Register endpoints marked [AllowAnonymous].

The authorization middleware checks for the presence of IAllowAnonymous metadata on the matched endpoint.

If present, the authorization filter immediately skips evaluation and allows the request to execute without credentials.

[AllowAnonymous] cannot be applied to endpoints that do not have authorization configured.

148

What is Imperative Authorization vs Declarative Authorization?

Declarative authorization uses attributes like [Authorize(Policy = “CanDelete”)] directly on classes and methods.

Declarative authorization is evaluated statically by the framework filter pipeline before the action method executes.

Imperative authorization is written manually inside method code using injected IAuthorizationService instances.

Imperative authorization is required when decisions depend on runtime database state, resource properties, or dynamic calculations.

Both approaches leverage the same underlying policy and handler architecture.

149

How do you implement Multi-Tenant Authorization in ASP.NET Core?

Multi-tenant applications isolate data and permissions across multiple distinct client organizations (tenants).

The tenant identifier is extracted early in the pipeline from subdomains, headers, or user JWT tenant claims.

Custom authorization handlers verify that the user’s TenantId claim matches the tenant context of the requested resource.

Combined with EF Core Global Query Filters, multi-tenant authorization guarantees zero cross-tenant data leakage.

Users belonging to Tenant A are forbidden from viewing or modifying records belonging to Tenant B.

150

How do Permission-Based Authorization and Dynamic Permissions work?

Permission-based authorization grants granular permissions (e.g., “products.create”, “orders.refund”) rather than coarse roles.

Users are assigned roles, and each role maps to a collection of granular permission claims stored in the database.

A custom authorization requirement and handler check if context.User.HasClaim(“Permission”, requiredPermission).

This eliminates hardcoded role names in controller code and allows administrators to reconfigure role permissions at runtime.

It provides enterprise-grade, fine-grained access control across large-scale software systems.

Level 16

Security, Cryptography & Threat Defense

10 Questions
151

How do you defend against Cross-Site Scripting (XSS) in ASP.NET Core?

XSS occurs when malicious JavaScript code is injected into web pages and executed in victim browsers.

Razor rendering engines automatically HTML-encode all variable output by default using @Model.Property.

Developers must never use @Html.Raw() on unvalidated, untrusted user inputs.

Content Security Policy (CSP) headers instruct browsers to restrict where scripts, styles, and fonts can load from.

AntiXSS HTML sanitization libraries like HtmlSanitizer strip dangerous tags before storing rich user content.

152

How does Cross-Site Request Forgery (CSRF) protection work in ASP.NET Core?

CSRF tricks an authenticated user’s browser into executing unauthorized actions on a trusted site using ambient cookies.

ASP.NET Core generates cryptographically secure antiforgery tokens using the Data Protection API.

One token is issued as an HTTP-only cookie, and a corresponding hidden token is embedded into form requests.

The server validates that both tokens match upon receiving POST requests using the [ValidateAntiForgeryToken] attribute.

For SPAs and APIs, storing tokens in secure cookies and setting SameSite=Strict cookies stops cross-site forgery.

153

How do you prevent SQL Injection vulnerabilities in ASP.NET Core?

SQL injection occurs when untrusted user strings are concatenated directly into raw database commands.

Entity Framework Core automatically parameterizes all LINQ queries and FromSqlInterpolated expressions.

When using raw ADO.NET or Dapper, always use parameterized commands with explicit DbParameter objects.

Never use string concatenation or string formatting to build dynamic SQL statements.

Apply least-privilege database user permissions to restrict attack blast radiuses if an injection vulnerability occurs.

154

What is the ASP.NET Core Data Protection API (DPAPI)?

The Data Protection API provides cryptographic encryption and decryption services for sensitive application data.

It protects session cookies, antiforgery tokens, password reset links, and authentication state.

Keys are rotated automatically on a scheduled basis (default: 90 days) and old keys are preserved for decryption.

In multi-server web farms, keys must be persisted centrally in Redis, Azure Key Vault, or network file shares.

Developers use IDataProtectionProvider and IDataProtector to encrypt and decrypt sensitive database columns.

155

How do you secure Sensitive Configuration Secrets in Production?

Production secrets like database connection strings and JWT signing keys must never be committed to source code repositories.

In local development, developers use the Secret Manager tool (dotnet user-secrets) to store credentials outside the project tree.

In production, applications load secrets from environment variables, Azure Key Vault, AWS Secrets Manager, or HashiCorp Vault.

Configuration providers load cloud vault secrets transparently into the unified IConfiguration hierarchy at application startup.

Access to production vaults is secured using managed cloud identities without storing static keys on disks.

156

How do you enforce HTTPS and HSTS in ASP.NET Core?

app.UseHttpsRedirection() redirects insecure plain HTTP requests to secure HTTPS endpoints with an HTTP 307 or 308 redirect.

HTTP Strict Transport Security (HSTS) instructs browsers to communicate with the domain exclusively over HTTPS for a defined duration.

HSTS is configured via builder.Services.AddHsts() and enabled in production pipelines using app.UseHsts().

HSTS protects users against man-in-the-middle attacks and SSL stripping attacks on public Wi-Fi networks.

Preload directives allow domains to be hardcoded into browser engines as HTTPS-only websites.

157

What are Security Headers and how do you configure them in ASP.NET Core?

Security headers instruct web browsers to activate built-in defense mechanisms against common web attack vectors.

X-Content-Type-Options: nosniff prevents MIME-type sniffing attacks on uploaded files.

X-Frame-Options: DENY protects against Clickjacking attacks by forbidding iframe embedding.

Content-Security-Policy (CSP) restricts executable scripts, preventing cross-site scripting and unauthorized resource loading.

Referrer-Policy: strict-origin-when-cross-origin protects user privacy when navigating external links.

Custom middleware or packages like NetEscapades.AspNetCore.SecurityHeaders apply these headers across all HTTP responses.

158

How do you defend against Distributed Denial of Service (DDoS) and Brute-Force Attacks?

Implement IP-based and user-based Rate Limiting middleware to throttle abusive request volumes automatically.

Enforce account lockout policies in ASP.NET Core Identity after five consecutive failed login attempts.

Use CAPTCHA challenges like Cloudflare Turnstile or Google reCAPTCHA on public registration and login forms.

Deploy cloud edge Web Application Firewalls (WAF) like Cloudflare or AWS Shield to absorb volumetric traffic.

Configure request body size limits ([RequestSizeLimit]) to prevent server memory exhaustion from oversized payloads.

159

What is Mass Assignment / Over-Posting and how do you prevent it?

Over-posting occurs when a client sends extra, unexpected JSON properties that bind directly to database entity models.

For example, an attacker appends “IsAdmin”: true to a registration JSON body, elevating their account privileges.

Prevent over-posting by using dedicated Data Transfer Objects (DTOs) for incoming request payloads rather than domain entities.

DTOs expose only the specific fields that clients are legitimately permitted to modify.

AutoMapper or explicit manual mapping maps validated DTO values onto entity properties safely.

160

What is Server-Side Request Forgery (SSRF) and how do you prevent it?

SSRF occurs when an attacker tricks the server into making HTTP requests to internal, non-public network infrastructure.

For example, supplying an internal IP address (169.254.169.254) to an image import feature fetches cloud metadata and credentials.

Prevent SSRF by strictly validating and whitelisting permitted domain names before issuing outbound HttpClient requests.

Block loopback addresses, internal private IP ranges (RFC 1918), and link-local cloud metadata addresses.

Use dedicated egress proxy gateways and isolate application server networks from internal management systems.

Level 17

Caching, Redis & SignalR Real-Time

10 Questions
161

What is the difference between In-Memory Caching and Distributed Caching?

In-Memory caching (IMemoryCache) stores cached items directly inside the local application server process RAM.

In-memory caching delivers near-zero latency but does not share cache state across multi-server web farm instances.

Distributed caching (IDistributedCache) stores cached data in an external, centralized caching cluster such as Redis.

Distributed caches share state seamlessly across all load-balanced web servers and persist cache data through server restarts.

Use in-memory cache for static single-server lookups and distributed cache for scalable cloud microservices.

162

How does IMemoryCache work in ASP.NET Core?

IMemoryCache provides thread-safe in-memory caching registered as a Singleton service using builder.Services.AddMemoryCache().

Methods include Get, Set, TryGetValue, and GetOrCreateAsync for thread-safe cache population.

Cache entries configure AbsoluteExpiration to expire at a fixed time, and SlidingExpiration to expire after inactivity.

Memory size limits and cache eviction callbacks can be configured to prevent out-of-memory crashes under heavy loads.

Cache priorities (Low, Normal, High, NeverRemove) determine eviction order when memory pressure limits are reached.

163

How do you implement Distributed Caching with Redis in .NET?

Add the Microsoft.Extensions.Caching.StackExchangeRedis package to the project.

Register the provider in Program.cs: builder.Services.AddStackExchangeRedisCache(options => options.Configuration = “redis:6379”).

Inject IDistributedCache into application services to perform GetAsync, SetAsync, and RemoveAsync operations.

Cached objects are serialized to byte arrays or JSON strings before saving to Redis keys.

Redis handles high-concurrency read operations, offloading massive query pressure from relational databases.

164

What is the Cache-Aside Pattern and how is it implemented?

The Cache-Aside pattern reads data from the cache first; if a cache miss occurs, it reads from the database and populates the cache.

Application code checks cache: var data = await cache.GetAsync(key); if data exists, return it immediately.

If null, query the database: var data = await db.GetAsync(id); then write to cache: await cache.SetAsync(key, data, ttl).

Subsequent requests retrieve the cached data directly until the expiration time-to-live (TTL) elapses.

When entities are updated or deleted, code explicitly invalidates or updates the corresponding cache key.

165

What is the Cache Stampede (Dog-Piling) problem and how do you prevent it?

Cache stampede occurs when a heavily requested cache key expires, causing thousands of concurrent requests to experience a cache miss.

All concurrent requests query the database simultaneously to recompute the same data, overwhelming and crashing the database.

Prevent stampede using locking primitives like SemaphoreSlim or Redis distributed locks (RedLock) so only one thread recomputes data.

Modern .NET provides HybridCache (introduced in .NET 9) which includes built-in concurrency locking and multi-tier L1/L2 caching.

Background cache pre-warming also updates keys before their expiration TTL elapses.

166

What is SignalR and how does real-time communication work?

SignalR is an ASP.NET Core library that enables server-side code to push real-time content to connected clients instantly.

SignalR automatically chooses the best transport mechanism supported by client and server: WebSockets, Server-Sent Events, or Long Polling.

WebSockets is the preferred full-duplex, low-latency transport protocol.

SignalR Hubs act as high-level communication pipelines where clients and servers invoke methods on each other bi-directionally.

Applications include live chat, real-time financial dashboards, multiplayer gaming, and collaborative document editing.

167

How do SignalR Hubs manage Connections and Groups?

A Hub class inherits from Hub or Hub<T> and exposes methods callable by connected JavaScript or mobile clients.

Each connected client receives a unique Context.ConnectionId managed by the hub lifetime.

Clients can be grouped into logical channels: await Groups.AddToGroupAsync(Context.ConnectionId, “Order_123”).

The server broadcasts messages to specific clients, user accounts (Clients.User), or groups (Clients.Group).

OnConnectedAsync and OnDisconnectedAsync handle connection establishment and cleanup lifecycle events.

168

How do you scale SignalR across multiple load-balanced servers?

In a load-balanced multi-server web farm, a client connected to Server A cannot receive messages broadcast from Server B.

A Backplane coordinates messages across all server nodes so every client receives broadcasts regardless of server connection.

Redis Backplane (Microsoft.AspNetCore.SignalR.StackExchangeRedis) publishes messages across servers using Redis Pub/Sub channels.

Alternatively, Azure SignalR Service offloads all persistent client WebSocket connections to fully managed cloud infrastructure.

Load balancers must configure Sticky Sessions (Session Affinity) to support fallback transports like Server-Sent Events.

169

What are Background Services and IHostedService in ASP.NET Core?

IHostedService provides a lifecycle contract for background tasks that run independently of incoming HTTP requests.

BackgroundService is an abstract base class implementing IHostedService, providing an ExecuteAsync(CancellationToken) method.

Background services start when the web host starts and stop gracefully when the application shuts down.

They are registered as singletons using builder.Services.AddHostedService<MyWorkerService>().

Use background services for queue consumers, scheduled reporting tasks, event-stream subscribers, and cache pre-warming.

170

How do you implement robust Background Job Scheduling in .NET?

Simple background tasks use built-in BackgroundService loops with PeriodicTimer for periodic intervals.

Enterprise applications require persistent job queues, retry policies, and dashboards provided by Hangfire or Quartz.NET.

Hangfire persists background job state into SQL Server or Redis, surviving application server crashes and restarts.

It supports fire-and-forget jobs, delayed jobs, recurring cron jobs, and continuations with built-in retry logic.

Hangfire provides a web-based administrative dashboard for monitoring and retrying failed jobs in real time.

Level 18

Frontend Integration (React, Next.js & Blazor)

10 Questions
171

What is Blazor and how do Blazor Server and Blazor WebAssembly differ?

Blazor is a Microsoft UI framework that allows building interactive web UIs using C#, HTML, and CSS instead of JavaScript.

Blazor Server executes UI code on the server, streaming UI updates and user events over a persistent SignalR WebSocket connection.

Blazor WebAssembly (WASM) downloads compiled C# assemblies and a .NET runtime into the browser, executing entirely client-side.

Blazor Server offers instant initial load times but requires persistent server connections and scales with server memory.

Blazor WebAssembly provides offline execution and zero server CPU load for UI rendering, but has a larger initial download size.

172

What are the .NET 8 Blazor United Render Modes?

.NET 8 unified Blazor Server and WebAssembly into a single full-stack web UI framework with flexible render modes.

Static Server-Side Rendering (Static SSR) generates plain HTML on the server like traditional MVC, delivering maximum SEO and speed.

Interactive Server runs component state on the server using SignalR for real-time reactivity.

Interactive WebAssembly runs component state in the client browser on WebAssembly.

Interactive Auto starts with Interactive Server immediately while WebAssembly assets download silently in the background.

173

How do React and Next.js SPAs consume ASP.NET Core Web APIs securely?

Frontend applications send asynchronous HTTP requests to ASP.NET Core APIs using Fetch or Axios.

Authentication is handled by sending JWT Bearer tokens inside the HTTP Authorization header: Bearer <token>.

Alternatively, HTTP-only secure cookies provide superior security against client-side JavaScript XSS token theft.

HTTP interceptors in Axios automatically attach tokens to requests and catch 401 Unauthorized errors to trigger token refresh.

CORS policies on the ASP.NET Core API must explicitly permit the frontend origin with credentials enabled.

174

How do you handle CORS when connecting React/Next.js to ASP.NET Core?

During local development and production, the frontend and backend typically run on different domains or ports.

Browsers block cross-origin requests unless the backend explicitly authorizes them via CORS headers.

In Program.cs, configure builder.Services.AddCors(options => options.AddPolicy(“AllowFrontend”, …)).

Specify WithOrigins(“https://my-frontend.com”), WithMethods(“GET”, “POST”, …), and WithHeaders(“Authorization”, …).

If sending authentication cookies, include AllowCredentials() and ensure WithOrigins specifies exact domain names, not wildcards.

175

How do you implement Server-Sent Events (SSE) vs WebSockets in ASP.NET Core?

WebSockets provides bidirectional, full-duplex communication where both client and server can transmit messages anytime.

Server-Sent Events (SSE) provides unidirectional streaming where the server pushes text events to the client over standard HTTP.

SSE is natively supported in browsers via EventSource without requiring third-party libraries or binary protocols.

In ASP.NET Core, SSE endpoints set Response.ContentType = “text/event-stream” and write data lines followed by double newlines.

Use WebSockets (SignalR) for interactive chat and gaming; use SSE for AI streaming responses and live notification feeds.

176

How do you stream LLM / AI responses from ASP.NET Core to a frontend?

Streaming AI responses requires sending token chunks to the client as they are generated rather than waiting for completion.

ASP.NET Core uses IAsyncEnumerable<string> in controller actions or Minimal API endpoints returning TypedResults.ServerSentEvents.

The endpoint consumes streaming tokens from OpenAI, Azure AI, or Ollama using await foreach (var chunk in stream).

Each token chunk is flushed to the HTTP response stream immediately using Response.Body.FlushAsync().

The frontend consumes the stream using standard Fetch with ReadableStream, updating the UI smoothly in real time.

177

How do you handle File Downloads and PDF generation in ASP.NET Core for frontends?

File downloads return a FileResult, FileStreamResult, or PhysicalFileResult with appropriate MIME types.

For generated PDFs or Excel sheets, use File(stream, “application/pdf”, “report.pdf”) to set the Content-Disposition header.

Streaming directly from disk or memory streams avoids loading entire file byte arrays into managed heap memory.

For massive files, set EnableRangeProcessing = true to support chunked resumable downloads in browsers.

Frontends trigger downloads using anchor tags with download attributes or handling blob streams in JavaScript.

178

What is the BFF (Backend for Frontend) Pattern?

The Backend for Frontend (BFF) pattern introduces dedicated server-side backend adapters tailored to specific frontend interfaces.

Instead of SPAs communicating directly with dozens of distributed microservices, they communicate with a single BFF server.

The BFF handles authentication cookies, token storage, request aggregation, and sensitive API secret management.

The BFF translates secure HTTP-only cookies from the browser into JWT Bearer tokens forwarded to downstream microservices.

This completely shields single-page applications from holding raw JWT tokens in browser memory.

179

How do you handle Global State and Error Handling in React with ASP.NET Core APIs?

React applications centralize server state using libraries like TanStack Query (React Query) or Redux Toolkit.

TanStack Query manages server caching, background refetching, deduplication, and optimistic UI updates automatically.

When ASP.NET Core returns standard RFC 7807 ProblemDetails on errors, Axios interceptors extract error dictionaries.

Forms map validation errors from ProblemDetails.errors directly to corresponding form inputs using React Hook Form.

Global error boundaries catch unhandled rendering exceptions and display user-friendly fallback interfaces.

180

How do you optimize Static Asset delivery and SPA fallback routing in ASP.NET Core?

ASP.NET Core can host compiled React, Angular, or Next.js static builds directly from the wwwroot folder.

app.UseStaticFiles() serves static JS, CSS, and image assets with caching and compression headers.

For client-side routing (React Router), app.MapFallbackToFile(“index.html”) routes all non-API paths back to index.html.

This allows users to reload deep client-side URLs like /dashboard/settings without receiving 404 Not Found errors.

API routes (/api/*) are mapped before fallback routes so API requests never accidentally serve the HTML index page.

Level 19

Automated Testing & CI/CD Pipelines

10 Questions
181

What is the Test Pyramid and how does it apply to ASP.NET Core?

The Test Pyramid is an architectural strategy organizing automated tests into three distinct layers based on speed and cost.

Unit tests form the broad foundation: fast, isolated, testing individual classes in memory with mock dependencies.

Integration tests form the middle layer: verifying that controllers, EF Core DbContext, and database queries work together.

End-to-End (E2E) tests form the narrow peak: testing the entire deployed system through the browser using Playwright or Selenium.

Maintaining a strong unit and integration foundation maximizes test coverage while keeping CI/CD pipeline execution fast.

182

What is the difference between xUnit , NUnit , and MSTest ?

xUnit is the modern, open-source standard framework used internally by Microsoft to test the .NET runtime and ASP.NET Core.

xUnit instantiates a fresh test class instance for every single test method, guaranteeing complete test isolation.

xUnit uses [Fact] for parameterless tests and [Theory] with [InlineData] for data-driven parameterized tests.

NUnit uses [Test], [TestCase], and maintains single class instances across methods unless configured otherwise.

MSTest is Microsoft’s legacy testing framework; xUnit remains the overwhelmingly preferred choice for modern .NET teams.

183

How do you perform Mocking in C# using Moq or NSubstitute ?

Mocking creates simulated substitute objects that mimic the behavior of real interface dependencies during unit tests.

NSubstitute syntax: var repo = Substitute.For<IOrderRepository>(); repo.GetByIdAsync(1).Returns(new Order());

Mocks isolate the System Under Test (SUT) from database connections, external HTTP APIs, and file systems.

Tests assert that specific methods were invoked with expected arguments: await repo.Received(1).SaveAsync(Arg.Any<Order>()).

Mocking enables millisecond-fast test execution and testing edge-case error scenarios like network timeouts safely.

184

What is WebApplicationFactory and how does it enable Integration Testing?

WebApplicationFactory<TProgram> bootstraps the entire ASP.NET Core application in memory for integration testing.

It starts a test server and provides an HttpClient preconfigured to route requests directly into the application pipeline.

Developers can override service registrations in Program.cs to substitute test databases or mock payment gateways.

Integration tests send real HTTP requests to endpoints, testing routing, model binding, filters, and middleware end-to-end.

It executes tests with near-native speed without requiring external IIS or Docker containers to be running.

185

What are Testcontainers and why are they superior to In-Memory Databases?

The EF Core In-Memory database provider does not behave like a real relational database engine (no foreign keys, no transactions).

Tests passing on the in-memory provider frequently fail in production against real SQL Server constraints.

Testcontainers is an open-source library that programmatically starts real Docker containers (SQL Server, PostgreSQL, Redis) during tests.

WebApplicationFactory connects directly to the containerized database, testing authentic SQL execution and migrations.

Containers spin up automatically before test suites execute and terminate immediately upon test completion.

186

How do you test Authenticated Endpoints using WebApplicationFactory ?

Testing [Authorize] endpoints requires supplying valid authentication credentials during integration tests.

One approach configures a custom AuthenticationHandler in tests using AddAuthentication(defaultScheme: “TestScheme”).

The test handler automatically constructs a ClaimsPrincipal with designated test user roles and claims.

Alternatively, integration tests can generate real JWT Bearer tokens in memory using the test signing key.

The token is attached to the test HttpClient: client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, token).

187

How do you measure Code Coverage in .NET?

Code coverage measures the percentage of application source code executed during automated test runs.

Tools like coverlet.collector generate standard coverage metrics (line, branch, and method coverage) during dotnet test.

Command: dotnet test –collect:”XPlat Code Coverage”.

ReportGenerator translates raw XML coverage reports into interactive, visual HTML dashboards.

CI/CD pipelines enforce quality gates, failing automated builds if code coverage drops below established project thresholds.

188

What is Mutation Testing and how does Stryker.NET work?

Mutation testing evaluates the actual quality and effectiveness of existing unit test suites.

Stryker.NET introduces deliberate bugs (“mutants”) into your C# source code (e.g., inverting > to <, altering boolean logic).

It then executes the test suite; if existing unit tests fail, the mutant is “killed” (test quality is verified).

If all unit tests still pass despite the mutant bug, the mutant “survived” (revealing a gap in test assertions).

Mutation testing prevents false confidence from high code coverage metrics that lack rigorous assertions.

189

How do you design a GitHub Actions CI/CD Pipeline for ASP.NET Core?

A GitHub Actions workflow (.github/workflows/dotnet.yml) triggers automatically on git push and pull request events.

Steps execute: checkout repository, setup .NET SDK, restore NuGet packages (dotnet restore), and compile code (dotnet build –no-restore).

Execute tests: dotnet test –no-build –verbosity normal –collect:”XPlat Code Coverage”.

Package application: dotnet publish -c Release -o ./publish.

Deploy artifact to Azure App Service, AWS ECS, or build a Docker container pushed to a container registry like Docker Hub or GitHub Packages.

190

What are Health Check UI and Prometheus Metrics in Production Monitoring?

The AspNetCore.HealthChecks.UI package provides a visual dashboard aggregating health check statuses across microservices.

Endpoints expose JSON health summaries that the UI polls periodically to display server status indicators.

For metrics, Prometheus-net exposes application telemetry (/metrics) capturing request rates, duration histograms, and GC memory.

Grafana dashboards query Prometheus metrics to visualize live traffic throughput, error spikes, and server CPU loads.

Alertmanager triggers real-time alerts when error rates exceed defined operational thresholds.

Level 20

Microservices, Cloud & Enterprise System Design

10 Questions
191

What is the difference between a Monolith, Modular Monolith, and Microservices?

A Monolith packages all application domain capabilities, business logic, and data access into a single deployable unit and database.

A Modular Monolith maintains a single deployable unit but strictly enforces boundaries between domain modules using clean interfaces.

Microservices divide the application into independent services, each with its own codebase, deployment pipeline, and database.

Monoliths offer simpler development, unified transactions, and zero network latency between components.

Microservices provide independent scaling, team autonomy, and technology diversity at the cost of distributed complexity.

192

What is an API Gateway and how do YARP and Ocelot work?

An API Gateway acts as the single unified entry point for all external client requests entering a microservices ecosystem.

It handles cross-cutting concerns: SSL termination, global authentication, rate limiting, request routing, and telemetry.

YARP (Yet Another Reverse Proxy) is Microsoft’s high-performance, highly customizable reverse proxy library built on ASP.NET Core.

Ocelot is an open-source .NET API Gateway library providing routing, aggregation, authentication, and load balancing.

Gateways shield internal microservice network topologies from public internet consumers.

193

How do you implement Asynchronous Messaging with RabbitMQ and MassTransit ?

Synchronous HTTP between microservices introduces tight coupling, cascading latency, and single-point-of-failure vulnerabilities.

Asynchronous messaging decouples services using message brokers like RabbitMQ, Azure Service Bus, or Apache Kafka.

MassTransit is an open-source distributed application framework providing a unified abstraction over message brokers in .NET.

Publishing an event: await publishEndpoint.Publish<OrderCreatedEvent>(new OrderCreatedEvent { OrderId = id }).

Consumers implement IConsumer<OrderCreatedEvent>, handling messages asynchronously with built-in retries and dead-letter queues.

194

What is the Outbox Pattern and why is it critical for Distributed Transactions?

Saving a database entity and publishing a message to a broker are two distinct operations that cannot share an atomic transaction.

If the database commit succeeds but the message broker crashes before publishing, the event is permanently lost.

The Outbox Pattern saves the domain entity and an Outbox message record into the same database within a single local transaction.

A background worker (like MassTransit or Quartz) continuously polls the Outbox table, publishes pending messages, and marks them processed.

This guarantees At-Least-Once Delivery without requiring complex, slow two-phase commit (2PC) distributed transactions.

195

What are CQRS and the Mediator Pattern ( MediatR )?

Command Query Responsibility Segregation (CQRS) separates data modification operations (Commands) from data retrieval operations (Queries).

Commands represent actions that alter state and return minimal data; Queries retrieve data without mutating system state.

MediatR is an in-process messaging library decoupling HTTP controllers from business service handlers.

Controllers dispatch requests: await mediator.Send(new CreateOrderCommand(…)).

A dedicated CreateOrderCommandHandler handles the command, isolating business logic and simplifying unit testing.

196

What is the Circuit Breaker Pattern and how does Polly implement it?

The Circuit Breaker pattern prevents an application from repeatedly calling a failing remote microservice or database.

The circuit has three states: Closed (normal operation), Open (failing fast without calling remote service), and Half-Open (testing recovery).

When consecutive error thresholds are exceeded, the circuit opens, returning immediate fallback errors without wasting network threads.

After a cooldown duration, the circuit transitions to Half-Open, sending trial requests to verify remote service health.

Microsoft.Extensions.Http.Resilience integrates Polly circuit breakers, retries, and rate limiters natively into IHttpClientFactory.

197

How do you implement Distributed Tracing with OpenTelemetry in .NET?

Distributed tracing tracks the journey of an HTTP request as it propagates across multiple distributed microservices.

OpenTelemetry provides a standardized vendor-neutral framework for collecting traces, metrics, and logs.

Activity and ActivitySource in .NET represent spans and traces, propagating W3C TraceContext headers (traceparent) across HTTP calls.

Registered using builder.Services.AddOpenTelemetry().WithTracing(b => b.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation().AddOtlpExporter()).

Traces export to observability platforms like Jaeger, Zipkin, Dynatrace, or Azure Application Insights for visual latency debugging.

198

How do you design for High Availability and Horizontal Scalability in ASP.NET Core?

Applications must be stateless so any incoming HTTP request can be served by any available server instance behind a load balancer.

Store session data, authentication state, and caches in external distributed stores like Redis rather than local server RAM.

Deploy application containers across multiple availability zones using orchestration platforms like Kubernetes or Azure Container Apps.

Configure auto-scaling rules based on CPU utilization, memory thresholds, or HTTP request queue depths.

Use database read replicas to offload read-heavy queries, and manage database connection pooling carefully.

199

What are Database Sharding and Read-Write Splitting?

Read-Write splitting directs all data-modifying commands (INSERT, UPDATE, DELETE) to a primary database instance.

All read-only queries are routed to one or more asynchronous read replicas, dramatically multiplying read throughput capacity.

Database Sharding partitions a massive database horizontally across multiple physical database servers based on a shard key.

For example, users with TenantId A–M store on Database Shard 1, and TenantId N–Z store on Database Shard 2.

Sharding overcomes physical storage limits and CPU bottlenecks for hyper-scale multi-million user applications.

200

SYSTEM DESIGN: Design an End-to-End Enterprise E-Commerce Platform with ASP.NET Core Full Stack.

The frontend utilizes Next.js for server-rendered product catalog pages, optimizing SEO and web vitals, backed by React for checkout.

Traffic enters through a Cloudflare CDN and WAF, terminating SSL and shielding against DDoS attacks.

YARP API Gateway handles edge routing, rate limiting, and authenticates JWT Bearer tokens before forwarding to microservices.

Microservices are structured around core business domains: Identity Service, Product Catalog Service, Order Service, and Payment Service.

Order and Payment services leverage Clean Architecture with CQRS, MediatR, and Entity Framework Core with SQL Server.

High-frequency product reads are cached using a Redis distributed cluster implementing the Cache-Aside pattern.

Asynchronous inter-service communication is orchestrated using MassTransit over RabbitMQ implementing the Outbox Pattern.

Resilience is enforced using Polly circuit breakers on all inter-service HTTP calls, and distributed tracing is unified via OpenTelemetry.

Database write-splitting routes reporting queries to read replicas, ensuring reliable scalability during high-traffic flash sale events.

Leave a Reply

Your email address will not be published. Required fields are marked *