Skip to main content

Amazon Interview .NET Core Interview Questions

Curated Amazon Interview-level .NET Core interview questions for developers targeting amazon interview positions. 148 questions available.

Last updated:

.NET Core Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of .NET Core interview questions and answers. This page contains expertly curated interview questions covering all aspects of .NET Core, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our .NET Core interview questions are designed to help you:

  • Understand core concepts and best practices in .NET Core
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next .NET Core interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic .NET Core concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

148 questions
Q1:

What is inheritance?

Entry

Answer

One class derives behavior from another using 

class Dog : Animal { }


Quick Summary: Inheritance lets a class (child) reuse and extend the behavior of another class (parent). The child inherits all public and protected members — no need to duplicate code. In C#: class Dog : Animal { }. Dog gets Animal's properties and methods automatically. Use it for "is-a" relationships: a Dog IS an Animal. Prefer composition over deep inheritance hierarchies.
Q2:

What is ASP.NET Core and why was it created?

Entry

Answer

ASP.NET Core is a modern, high-performance, cross-platform framework for building web applications and APIs that can run on Windows, Linux, and macOS.

It was created to overcome limitations of the old ASP.NET Framework such as heavy runtime dependency on the full .NET Framework, tight coupling to IIS, poor modularity, and difficulty integrating with modern CI/CD and containerized environments.

ASP.NET Core introduces a lightweight runtime, a fully modular component system, built-in dependency injection, a unified hosting model, and a redesigned request pipeline focused on speed, flexibility, and cloud readiness.

Quick Summary: ASP.NET Core was built as a complete rewrite of classic ASP.NET — cross-platform (runs on Linux/Mac/Windows), open-source, and much faster. The old framework was Windows-only, tightly coupled to IIS, and carried legacy baggage. ASP.NET Core is lean, built around middleware, native dependency injection, and async by default — designed for cloud and containers.
Q3:

Explain the ASP.NET Core hosting model (Host Builder + Kestrel + Startup flow).

Entry

Answer

ASP.NET Core uses a unified Host (Generic Host / Web Host) that wires together configuration, logging, dependency injection, environment, and the HTTP pipeline.

  • The host sets up configuration (appsettings, environment variables, command line, etc.).
  • It constructs the DI container and registers application services.
  • It configures and starts Kestrel as the web server.
  • It builds the middleware pipeline and endpoint routing (MVC, Razor Pages, minimal APIs).

The high-level flow is: Host ? Kestrel ? Middleware pipeline ? MVC / Razor ? View or JSON result. This gives full low-level control over startup and behavior.

Quick Summary: The Generic Host (IHostBuilder) sets up DI, configuration, and logging. WebApplication.CreateBuilder() builds it for web apps. Kestrel (the built-in HTTP server) listens for connections. Program.cs wires everything up — services, middleware pipeline, and the app start. No Startup.cs is required in .NET 6+ with the minimal hosting model.
Q4:

What is Kestrel and why does ASP.NET Core use it?

Entry

Answer

Kestrel is the built-in, cross-platform, high-performance web server for ASP.NET Core.

It is optimized for asynchronous I/O, low memory overhead, and extremely fast request handling, making it suitable for both self-hosted scenarios and running behind reverse proxies such as Nginx, Apache, or IIS.

ASP.NET Core uses Kestrel because it delivers excellent throughput, works on all supported platforms, integrates deeply with the middleware pipeline, and gives developers full control over how requests are processed.

Quick Summary: Kestrel is ASP.NET Core's built-in, cross-platform HTTP server — fast, lightweight, and runs on any OS without IIS. In production, it's typically placed behind a reverse proxy (nginx, IIS) for TLS termination and load balancing. Kestrel handles the raw HTTP connections; the proxy handles the internet-facing concerns.
Q5:

Explain Middleware and the purpose of the ASP.NET Core Request Pipeline.

Entry

Answer

Middleware are components that process HTTP requests and responses in a sequence known as the request pipeline.

  • Each middleware can inspect or modify the incoming request.
  • It may call the next middleware in the pipeline or short-circuit and generate a response.
  • On the way back, it can also modify the outgoing response.

The pipeline is used to implement cross-cutting concerns such as authentication, logging, routing, static file handling, CORS, and endpoint execution. This model replaces the older HTTP modules/handlers, offering a more flexible and composable design.

Quick Summary: Middleware are components that form the request pipeline — each one receives the request, does work, then calls the next. Authentication, routing, exception handling, response compression all work this way. Each middleware is added in Program.cs via app.Use*() methods. The pipeline runs in order on request, and reverse on response.
Q6:

Why does the order of middleware matter so much?

Entry

Answer

Middleware executes in the exact order in which it is registered. Because each middleware can decide whether to pass control to the next component, incorrect ordering can break critical behaviors.

For example:

  • Exception-handling middleware must be early in the pipeline to catch downstream errors.
  • Authentication must run before authorization and MVC.
  • Static file middleware should run before MVC to avoid unnecessary controller execution.

ASP.NET Core does not automatically correct the order, so developers are responsible for composing the pipeline correctly.

Quick Summary: Each middleware wraps the next one in the pipeline. If authentication middleware comes after routing, unauthenticated requests still hit the router. If static files middleware comes after routing, static files would fail to serve. Wrong order causes subtle bugs: put exception handling first, then HSTS, then routing, then authentication, then authorization.
Q7:

What is Dependency Injection in ASP.NET Core and why is it built-in?

Entry

Answer

Dependency Injection (DI) in ASP.NET Core is the built-in mechanism for constructing and wiring application services.

The framework provides a first-class DI container that:

  • Creates and manages service lifetimes.
  • Resolves dependencies for controllers, Razor Pages, middleware, and other components.
  • Encourages testable, loosely coupled code.

Having DI built-in removes the need for static helpers or service locators and standardizes how dependencies are managed across the whole stack.

Quick Summary: DI is built into ASP.NET Core because it's essential for testability, loose coupling, and lifecycle management. Instead of services creating their dependencies (new DbContext()), ASP.NET Core injects them. The DI container manages object lifetimes and wires everything together. You register services in Program.cs and request them via constructor parameters.
Q8:

Explain the three DI lifetimes (Transient, Scoped, Singleton).

Entry

Answer

ASP.NET Core's DI container supports three main lifetimes:

  • Transient – A new instance is created every time it is requested. Best for lightweight, stateless services.
  • Scoped – One instance per HTTP request. Ideal for services that work with per-request data such as unit-of-work or context services.
  • Singleton – A single instance is created and shared for the lifetime of the application. Must be thread-safe and used carefully around shared state.

Choosing the wrong lifetime can lead to concurrency bugs, memory leaks, or stale data.

Quick Summary: Transient: new instance created every time the service is requested — for lightweight, stateless services. Scoped: one instance per HTTP request — for DbContext and request-specific services. Singleton: one instance for the app lifetime — for caches, config wrappers, and truly shared services. Injecting a Scoped service into a Singleton causes a captive dependency bug.
Q9:

What is Configuration in ASP.NET Core and how does it work?

Entry

Answer

ASP.NET Core uses a flexible, layered configuration system where multiple providers are combined to produce the final configuration.

Common sources include:

  • appsettings.json and appsettings.{Environment}.json
  • Environment variables
  • Command-line arguments
  • User Secrets and Azure Key Vault
  • In-memory configuration

Later providers override earlier ones, enabling environment-specific overrides and secure storage of secrets. Configuration values can be bound directly to strongly typed options classes.

Quick Summary: ASP.NET Core's configuration system reads from layered sources: appsettings.json → appsettings.{Environment}.json → environment variables → command-line args → secrets. Later sources override earlier ones. Access via IConfiguration["Section:Key"] or bind entire sections to strongly-typed options classes with IOptions.
Q10:

What is the purpose of IOptions, IOptionsSnapshot, and IOptionsMonitor?

Entry

Answer

These abstractions implement the Options pattern for working with configuration-bound classes.

  • IOptions<T> – A singleton snapshot of configuration, read once at startup.
  • IOptionsSnapshot<T> – A scoped snapshot that is recalculated per request; useful for web apps where config might change between requests.
  • IOptionsMonitor<T> – Supports change notifications and is ideal for long-lived components that need to react to configuration changes at runtime.

They allow strongly typed configuration without scattering configuration reads throughout the codebase.

Quick Summary: IOptions: reads config once at startup — singleton, doesn't pick up changes after app starts. IOptionsSnapshot: reads config per request — picks up changes between requests. IOptionsMonitor: reads config and reacts to changes in real-time via OnChange callback — ideal for configs that need live updates without restart.
Q11:

What is Routing in ASP.NET Core?

Entry

Answer

Routing maps incoming HTTP requests (URL + HTTP method) to application endpoints such as controllers, actions, Razor Pages, or minimal APIs.

ASP.NET Core uses Endpoint Routing, which matches routes early in the pipeline, attaches metadata (like authorization policies), and then later executes the matched endpoint. It supports route templates, constraints, defaults, and custom route patterns.

Quick Summary: Routing maps incoming HTTP requests to handler endpoints (controller actions, Razor Pages, minimal API handlers). ASP.NET Core uses endpoint routing: route matching and endpoint execution are separate phases. Routes are defined via attribute routing ([Route], [HttpGet]) or convention-based routing. Route templates ({controller}/{action}/{id?}) define the URL pattern.
Q12:

Compare Conventional Routing vs Attribute Routing.

Entry

Answer

Conventional routing defines route patterns centrally (e.g., {controller}/{action}/{id?}), which are then applied to many controllers and actions following a naming convention. It is useful for large apps with predictable URL structures.

Attribute routing defines routes directly on controllers and actions via attributes such as [Route], [HttpGet], etc. It is more expressive and better suited for APIs or scenarios where each endpoint may have unique or non-standard URL patterns.

Quick Summary: Conventional routing defines a central route template: app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"). Attribute routing puts routes directly on controllers/actions: [Route("api/users")]. Attribute routing is more explicit and predictable for APIs. Conventional routing is simpler for traditional MVC apps with many similar routes.
Q13:

What is Model Binding?

Entry

Answer

Model binding is the process of converting HTTP request data into .NET objects that are used as parameters to controller actions or Razor Page handlers.

It pulls values from sources like route data, query strings, form fields, headers, and cookies, then converts and populates complex types, collections, and nested objects. This lets you work with rich, strongly typed parameters instead of manually parsing the request.

Quick Summary: Model binding automatically maps HTTP request data (form fields, route values, query strings, JSON body) to method parameters and model properties. When an action receives a CreateUserRequest parameter, ASP.NET Core reads the request body and populates every matching property automatically. No manual request parsing needed.
Q14:

What is Model Validation and how does it work?

Entry

Answer

Model validation runs immediately after model binding and before the action method executes.

  • Validation rules are typically expressed via data annotations (e.g., [Required], [Range]).
  • Errors are added to ModelState.
  • Controllers or Razor Pages check ModelState.IsValid to decide whether to continue or return validation errors.

Validation can also be implemented via IValidatableObject or custom validators, ensuring that only valid data reaches business logic.

Quick Summary: Model validation checks that bound model properties satisfy their data annotation constraints ([Required], [MaxLength], [EmailAddress], [Range]). After binding, ASP.NET Core populates ModelState — if invalid, ModelState.IsValid is false and you return a 400 response. FluentValidation is a popular alternative to data annotations for complex rules.
Q15:

What are Filters and why are they important?

Entry

Answer

Filters are extensibility points in the MVC and Razor Pages pipeline that allow code to run before or after critical stages.

Types of filters include:

  • Authorization filters
  • Resource filters
  • Action filters
  • Exception filters
  • Result filters

They are ideal for cross-cutting concerns like logging, caching, auditing, authorization, and exception handling without polluting controller or page logic.

Quick Summary: Filters run at specific points in the MVC pipeline — before/after model binding, action execution, result execution, and exception handling. Types: Authorization (runs first), Resource, Action, Result, Exception. Filters are cleaner than middleware for MVC-specific cross-cutting concerns like logging action parameters or adding response headers per action.
Q16:

What are Razor Views?

Junior

Answer

Razor Views are templates that combine HTML with C# using the Razor syntax to render dynamic HTML responses.

Razor is lightweight, fast, and avoids the heavy view state and page lifecycle of WebForms. Views are usually driven by strongly typed models, enabling clean separation of concerns between UI and logic.

Quick Summary: Razor Views are .cshtml files that combine HTML markup with C# code to generate dynamic HTML responses. They use the Razor syntax (@Model.Name, @foreach, @if) to embed C# expressions. The view gets a strongly-typed Model from the controller, making it type-safe. The Razor compiler converts .cshtml to C# classes at build or runtime.
Q17:

Explain Layouts, Partial Views, and View Components.

Junior

Answer

Layouts define a shared page shell (e.g., header, footer, navigation) used across many views.

Partial Views are reusable view fragments for rendering common UI pieces (e.g., a login panel or a list of items).

View Components encapsulate both rendering logic and view; they behave like mini-controllers plus views and are ideal for widgets (menus, dashboards, notifications) that need their own logic and markup.

Quick Summary: Layout: the shared template (_Layout.cshtml) that wraps all views — navigation, header, footer, common CSS/JS. Partial View: a reusable fragment rendered inside a view (like a product card). View Component: like a mini-controller+view — has its own logic, can query the database, and renders independently. More powerful than Partial Views for complex UI pieces.
Q18:

What are Tag Helpers?

Junior

Answer

Tag Helpers let you apply server-side behavior to HTML elements using natural HTML syntax.

Examples include form, input, link, and environment helpers. They integrate tightly with routing, model binding, and validation, improving readability and tooling support (IntelliSense) compared to traditional HTML helpers.

Quick Summary: Tag Helpers are C# classes that transform HTML elements in Razor views — they look like HTML attributes but are processed server-side. Home generates the correct URL automatically. They're more IDE-friendly and readable than HTML Helpers (@Html.ActionLink()), and support IntelliSense and validation.
Q19:

What is TempData and how is it different from ViewData/ViewBag?

Junior

Answer

ViewData and ViewBag are used to pass data from controllers to views within the same request.

  • ViewData is a Dictionary<string, object>.
  • ViewBag is a dynamic wrapper around ViewData.

TempData persists data across a single redirect and is cleared once read. It is backed by cookies or session and is ideal for messages (e.g., success notifications) that survive a redirect.

Quick Summary: TempData persists for one redirect cycle — you set it before a redirect and read it after. Useful for flash messages ("Record saved!"). ViewData is a dictionary passed from controller to view within one request. ViewBag is dynamic wrapper over ViewData. TempData uses session or cookies behind the scenes; ViewData and ViewBag don't survive redirects.
Q20:

What is Anti-Forgery and why is it required?

Junior

Answer

Anti-forgery protection defends against Cross-Site Request Forgery (CSRF) attacks.

ASP.NET Core generates a pair of correlated tokens: one stored in a cookie and one embedded in the form. On POST, both must be present and valid. This ensures that state-changing requests originate from the legitimate site and user, not from a malicious third-party page.

Quick Summary: Anti-Forgery tokens prevent Cross-Site Request Forgery (CSRF) attacks where a malicious site tricks a user's browser into submitting a form to your app. ASP.NET Core generates a hidden form token and a cookie token. On form submission, it verifies both match. The [ValidateAntiForgeryToken] attribute or Razor form tag helpers handle this automatically.
Q21:

How does ASP.NET Core handle static files and why is the middleware special?

Junior

Answer

Static files (CSS, JavaScript, images, etc.) are served by the Static File Middleware, which is usually placed early in the pipeline.

When a request matches a static file in wwwroot (or another configured folder), the middleware serves it directly and short-circuits the pipeline, bypassing MVC and other components. This leads to better performance and avoids unnecessary computation for simple file requests.

Quick Summary: The Static Files middleware serves files from wwwroot directly — HTML, CSS, JS, images — without going through MVC routing. It must be placed before UseRouting() and UseAuthentication() or it would require authentication to serve a CSS file. It short-circuits the pipeline for matching static files, returning them directly without controller processing.
Q22:

What is the difference between the Generic Host and Web Host in ASP.NET Core?

Junior

Answer

Earlier ASP.NET Core versions used WebHost to configure web-specific hosting (Kestrel, IIS integration, MVC, etc.).

The newer Generic Host unifies hosting for all app types (web, background services, workers, gRPC, SignalR) under a single abstraction.

  • Generic Host centralizes DI, configuration, and logging.
  • It supports non-web workloads and multiple hosted services in the same process.
  • For web apps, Generic Host wires in WebHost-like features such as Kestrel and endpoint routing under the hood.
Quick Summary: Web Host (IWebHostBuilder) was the original ASP.NET Core host — web-specific, tied to HTTP. Generic Host (IHostBuilder) is the modern replacement — it supports web, workers, console apps, and Windows services all with the same pattern. Generic Host is recommended for all new apps; Web Host is legacy. WebApplication builder (.NET 6+) wraps Generic Host.
Q23:

Explain the Application Lifetime events in ASP.NET Core (IHostApplicationLifetime).

Junior

Answer

IHostApplicationLifetime (renamed to IHostApplicationLifetime / IHostApplicationLifetime in newer versions) exposes three key notifications:

  • ApplicationStarted – Fired when the app is fully started and ready to serve requests.
  • ApplicationStopping – Fired when the app begins a graceful shutdown (e.g., SIGTERM in containers).
  • ApplicationStopped – Fired when shutdown is complete and cleanup has finished.

These events are used to warm up caches, start or stop background tasks, flush logs, and release resources in cloud and container environments.

Quick Summary: IHostApplicationLifetime provides three events: ApplicationStarted (app is fully started), ApplicationStopping (shutdown triggered, still running), ApplicationStopped (shutdown complete). Use these to run startup logic (warm caches) or cleanup (flush logs, close connections). Inject IHostApplicationLifetime wherever you need lifecycle hooks.
Q24:

What is the purpose of the Web Root and why is it separated from the Content Root?

Junior

Answer

The Content Root is the base path for application code, views, and configuration files.

The Web Root (usually wwwroot) is the publicly exposed folder for static files such as CSS, JS, and images.

Separating them ensures that sensitive assets like configuration files, views, and binaries are not accidentally served over HTTP. Only files under Web Root are directly reachable by clients.

Quick Summary: Content Root is the base directory of the application — where appsettings.json, views, and application files live. Web Root (wwwroot) is the subdirectory served as static files to browsers. The separation means the app can serve only the intentional public directory without exposing source files, config, or dlls to browsers.
Q25:

Explain the difference between Use, Run, and Map in middleware configuration.

Junior

Answer

  • Use – Adds middleware that can process the request and optionally call the next middleware via a next delegate.
  • Run – Adds terminal middleware that does not call the next component; it ends the pipeline.
  • Map – Branches the pipeline based on the request path, creating sub-pipelines for specific URL segments.

Together, they give fine-grained control over the shape and branching of the request pipeline.

Quick Summary: Use(): adds middleware that can call next — used for middleware that performs work and continues the pipeline. Run(): terminal middleware — never calls next, short-circuits the pipeline. Map(): branches the pipeline based on a URL prefix — creates a sub-pipeline for that branch. Use is the most common; Run ends the pipeline; Map enables path-based branching.
Q26:

What is Environment-based configuration and why is it essential?

Junior

Answer

ASP.NET Core supports named environments such as Development, Staging, and Production, typically controlled by the ASPNETCORE_ENVIRONMENT variable.

Environment controls:

  • Which configuration files are loaded (e.g., appsettings.Development.json).
  • Whether detailed error pages are shown.
  • Which services or features are enabled (e.g., runtime compilation only in Development).

Environment-based configuration prevents debug info and dev-only behaviors from leaking into production.

Quick Summary: ASPNETCORE_ENVIRONMENT (Development, Staging, Production) controls which appsettings.{env}.json file loads, enables/disables developer exception pages, and controls logging verbosity. IWebHostEnvironment.IsDevelopment() lets code behave differently per environment. Essential for showing detailed errors in dev and hiding them in production.
Q27:

What are Secrets in ASP.NET Core, and how are they different from configuration files?

Junior

Answer

User Secrets are a development-only feature for storing sensitive values (API keys, connection strings) outside the project tree.

  • They are not checked into source control.
  • They are only used for the Development environment.
  • They override configuration from JSON files.

In production, secrets should come from environment variables, Azure Key Vault, or similar secure stores, not from JSON configuration files.

Quick Summary: Secrets (User Secrets in dev, Azure Key Vault in production) store sensitive values (connection strings, API keys) outside appsettings.json so they're never committed to source control. In development, dotnet user-secrets stores them in a local JSON file outside the project. In production, inject them via environment variables or a secrets manager.
Q28:

Explain the Options Pattern and why it’s preferred over directly reading from configuration.

Junior

Answer

The Options Pattern binds configuration sections to strongly typed classes and injects them via IOptions<T>, IOptionsSnapshot<T>, or IOptionsMonitor<T>.

Benefits include:

  • Centralized configuration mapping and validation.
  • No magic strings scattered throughout the code.
  • Ability to reload or react to config changes.
  • Cleaner separation of configuration from business logic.
Quick Summary: The Options Pattern binds a configuration section to a strongly-typed class (services.Configure(config.GetSection("MySection"))). You inject IOptions and access typed properties instead of error-prone string keys. Supports validation, change tracking, and makes configuration testable and refactorable with compile-time safety.
Q29:

What is Razor View Compilation and why does it matter?

Junior

Answer

Razor View Compilation converts .cshtml files into C# classes and compiles them into assemblies.

  • Runtime compilation – Views are compiled on first use; flexible but slower for initial requests.
  • Precompilation – Views are compiled at build/publish time; improves startup and reduces CPU at runtime.

Production apps typically use precompiled views to improve startup time and performance.

Quick Summary: In .NET 6+, Razor views are compiled at publish time by default — no .cshtml files are needed in production, and no runtime compilation happens. This improves startup performance and deployment simplicity. In development, runtime compilation is enabled via Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation so changes are picked up without rebuild.
Q30:

What is the View Engine and how does Razor differ from classic engines?

Junior

Answer

The View Engine is responsible for locating and rendering views from templates.

Razor differs from older engines by:

  • Using C# instead of server controls or code-behind pages.
  • Eliminating view state and page lifecycle complexity.
  • Producing clean HTML with async support.
  • Providing strong tooling and compile-time checks.
Quick Summary: The Razor view engine compiles .cshtml files to C# classes that inherit RazorPage. The Execute() method generates the HTML. The engine resolves views by convention (/Views/{Controller}/{Action}.cshtml). Multiple engines can coexist — ASP.NET Core supports registering custom view engines alongside Razor.
Q31:

What are Tag Helper Scopes and how do they improve structure?

Junior

Answer

Tag Helpers operate within the HTML element tree and can apply behavior to all nested content.

Scoped helpers like <environment> wrap child elements to conditionally render sets of tags based on environment, reducing duplication and improving structure.

They help apply consistent behavior (e.g., script loading, validation attributes) across entire sections of the UI.

Quick Summary: Tag Helper scope is controlled by @addTagHelper and @removeTagHelper directives in _ViewImports.cshtml. You can add tag helpers globally (for the whole app) or restrict them to specific namespaces and assemblies. This prevents conflicts when two tag helpers process the same HTML element and lets teams control which tag helpers are available in which views.
Q32:

What is ViewData, ViewBag, and TempData?

Junior

Answer

  • ViewData – A Dictionary<string, object> for passing data from controller to view in the same request.
  • ViewBag – A dynamic wrapper around ViewData for more convenient syntax.
  • TempData – Persists data across one redirect; cleared after it is read.

ViewData/ViewBag are for same-request communication; TempData is designed for redirect scenarios such as Post-Redirect-Get.

Quick Summary: ViewData: dictionary, requires casting when reading, ViewData["Title"] = "Home". ViewBag: dynamic wrapper over ViewData — ViewBag.Title = "Home". TempData: survives a redirect — stored in cookie or session. All three pass data from controller to view within a request. ViewData and ViewBag are equivalent; TempData is the only one that persists across redirects.
Q33:

Explain Endpoint Routing in detail.

Junior

Answer

Endpoint Routing decouples route matching from endpoint execution.

  • UseRouting() runs early, matches the request to an endpoint, and attaches endpoint metadata.
  • Middleware such as authentication and authorization can inspect endpoint metadata.
  • UseEndpoints() executes the matched endpoint (controller, Razor Page, minimal API).

This improves performance, centralizes routing, and makes it easier to apply policies based on endpoint metadata.

Quick Summary: Endpoint Routing separates route matching from execution. UseRouting() matches the request to an endpoint and stores it in HttpContext. UseAuthorization() can then check the matched endpoint's metadata (including auth requirements) before execution. UseEndpoints() executes the matched endpoint. This separation allows middleware to inspect the matched route before execution.
Q34:

What is Model Binding Value Providers?

Junior

Answer

Value Providers are components in the model binding system that know how to fetch data from specific sources:

  • Route values
  • Query strings
  • Form data
  • Headers
  • Cookies

Model binding queries these providers in order to construct complex models from the incoming HTTP request.

Quick Summary: Model Binding uses Value Providers to read data from different parts of the request. Built-in providers: FormValueProvider (form data), RouteValueProvider (route segments), QueryStringValueProvider (query string), HeaderValueProvider, and BodyValueProvider (JSON/XML body). Custom Value Providers let you read from cookies, services, or any custom source.
Q35:

Explain Custom Model Binding and when it is required.

Junior

Answer

Custom Model Binding is used when default binding cannot map request data to models correctly.

Typical use cases:

  • Non-standard data formats.
  • Combining multiple values into a single complex object.
  • Parsing custom header or route patterns.

Implementing IModelBinder or using custom attributes provides full control over how request data is translated into .NET types.

Quick Summary: Custom Model Binders handle types that the default binder can't bind — enums from string aliases, comma-separated lists to arrays, complex query parameter formats, or binding from non-standard locations. Implement IModelBinder, return the constructed object, and register it with ModelBinderProviders in MVC options.
Q36:

What is ModelState and why is it crucial?

Mid

Answer

ModelState is a dictionary that stores the results of model binding and validation.

  • It tracks whether binding succeeded for each field.
  • It collects validation errors and messages.
  • ModelState.IsValid indicates whether the model is safe to use.

Actions should check ModelState to avoid operating on invalid data and to return meaningful error messages to clients.

Quick Summary: ModelState is a dictionary of property names to validation states populated after model binding. It tracks which fields have errors and what those errors are. ModelState.IsValid tells you if all validations passed. In Razor views, asp-validation-for and validation summary tag helpers display ModelState errors next to the relevant fields.
Q37:

What are Filters and what are their use cases?

Mid

Answer

Filters plug into the MVC and Razor Pages lifecycle at well-defined points.

Common use cases:

  • Authorization checks.
  • Logging and diagnostics.
  • Caching and response shaping.
  • Exception handling and error translation.
  • Pre/post action logic such as measuring execution time.
Quick Summary: Filters add cross-cutting behavior at specific pipeline stages: AuthorizationFilter (access control), ResourceFilter (caching, short-circuit), ActionFilter (pre/post action execution — logging, validation), ResultFilter (transform result), ExceptionFilter (handle exceptions per action). Scope: global, per-controller, per-action. Ordered by scope and then IOrderedFilter priority.
Q38:

What is an Exception Filter vs Middleware Exception Handling?

Mid

Answer

Exception middleware (e.g., UseExceptionHandler) sits high in the pipeline and can catch exceptions from the entire app, including non-MVC endpoints.

Exception Filters run only within the MVC pipeline and can convert exceptions to action results at the controller/action level.

Best practice is to use middleware for global exception handling and filters for MVC-specific customization.

Quick Summary: Exception Filters catch exceptions thrown by MVC actions and result execution — they run late in the MVC pipeline. Middleware exception handling (UseExceptionHandler) catches exceptions from the entire pipeline — including routing, authorization, and any middleware. Middleware catches more broadly; Exception Filters give you MVC context (current controller, action, route data).
Q39:

Explain ViewComponents and how they differ from Partial Views.

Mid

Answer

View Components combine rendering logic and a view into a reusable UI block, with full support for DI and testability.

Partial Views are simple reusable view fragments with no independent logic; they rely on the parent view's model.

View Components are ideal when the UI fragment needs its own data retrieval and business logic.

Quick Summary: ViewComponents have their own controller logic (InvokeAsync()) that can inject services, run async database queries, and return a view. Partial Views are simple, stateless — they just render their template with a model passed in. ViewComponents are reusable, independently testable UI widgets; Partial Views are simple HTML fragments.
Q40:

What is the Anti-Forgery System in ASP.NET Core?

Mid

Answer

The Anti-Forgery system protects against CSRF attacks by issuing two related tokens:

  • A cookie token stored in the browser.
  • A form/request token embedded in forms or headers.

On POST (or unsafe verbs), the server validates that both tokens are present and match. If not, the request is rejected. This ensures that only requests initiated from the legitimate site using the correct user context are accepted.

Quick Summary: Anti-Forgery generates a hidden __RequestVerificationToken in forms and a separate cookie. On submission, ASP.NET Core validates that both the form token and cookie token match (same origin, same user). A CSRF attack from a different origin can't read the cookie, so it can't forge a valid token pair. Applied automatically with Razor form tag helper.
Q41:

Explain how Static Files Middleware works and why it must be placed early.

Mid

Answer

The Static Files Middleware serves files directly from the configured web root without invoking MVC or other higher-level components.

It should be placed early in the pipeline so that requests for static resources are short-circuited quickly, improving performance and avoiding unnecessary processing by downstream middleware or controllers.

Quick Summary: Static Files middleware intercepts requests before routing. It maps the request path to the file system path under wwwroot. If the file exists, it sets appropriate content-type and cache headers and returns it directly — no MVC involvement. Placing it after authentication middleware would require login to load CSS files, breaking all anonymous pages.
Q42:

What is the Application Model in MVC and why do enterprise apps customize it?

Mid

Answer

The Application Model is MVC’s internal representation of controllers, actions, filters, route metadata, and parameters.

Enterprise systems customize it to enforce conventions like automatic versioning, uniform route naming, attribute injection, and cross-team architectural consistency.

Quick Summary: The Application Model (ApplicationModel, ControllerModel, ActionModel, ParameterModel) is an in-memory graph of all MVC controllers, actions, and their metadata. Conventions (IApplicationModelConvention) can modify this model at startup — adding routes, changing filters, or renaming actions globally. Enterprises use conventions instead of scattering attributes everywhere.
Q43:

Explain View Components and why they are better than Partial Views.

Mid

Answer

View Components bundle UI logic + view together and do not run through the MVC pipeline.

They support DI, encapsulate logic, and provide reusable & testable UI widgets, unlike partial views which render only markup.

Quick Summary: ViewComponents are more powerful than Partial Views because they have their own InvokeAsync() that runs server logic — dependency injection, async database queries — before rendering. Partial Views receive a model passed in from the calling view and just render it. ViewComponents encapsulate UI + logic together; Partial Views are just reusable HTML snippets.
Q44:

What is Feature Slicing and why is it replacing Layered Architecture in ASP.NET Core?

Mid

Answer

Feature Slicing groups features (Orders, Billing) instead of layers (Controllers, Views). It reduces folder noise, improves modularity, and scales better for large teams.

Quick Summary: Feature slicing organizes code by business feature — UserFeature/ contains its controller, service, repository, and views together. Layered architecture separates by concern — all controllers in one folder, all services in another. Feature slicing scales better: you touch one folder for one feature instead of jumping across the entire codebase.
Q45:

How does ASP.NET Core prevent request body overconsumption?

Mid

Answer

ASP.NET Core enforces request size limits, form limits, upload limits, and aborts oversized bodies. It uses streamed reading to avoid memory spikes.

Quick Summary: ASP.NET Core limits request body size via IIS (maxAllowedContentLength), Kestrel (MaxRequestBodySize), and the request body reading limits. By default, Kestrel limits request bodies to 30MB. You can reduce this per-action with [RequestSizeLimit(1000000)] or disable the limit for file upload endpoints that need it.
Q46:

What is Razor Class Library (RCL) and why do large companies use it?

Mid

Answer

RCL packages reusable UI components, views, layouts, and static files. Enterprises use it for shared branding, modular UI, and multi-project consistency.

Quick Summary: A Razor Class Library (RCL) is a class library that contains Razor views, pages, and static assets packaged as a NuGet. Teams share UI components across multiple ASP.NET Core apps from a central package. Large companies use RCLs to enforce consistent UI components (admin panels, login pages) across many internal applications without duplicating code.
Q47:

Explain how the Model Validation Pipeline works.

Mid

Answer

Validation runs after model binding. Attributes and custom validators populate ModelState. MVC may short-circuit execution if validation fails.

Quick Summary: After model binding, ASP.NET Core runs validators in this order: data annotation validators ([Required], [Range]), then IValidatableObject.Validate() for cross-property validation, then custom ValidationAttribute classes. Results populate ModelState. FluentValidation replaces this with a fluent DSL registered as a model validator. The pipeline is extensible via IModelValidator.
Q48:

What are Filters in MVC and how are the filter types ordered?

Mid

Answer

Filter order: Authorization ? Resource ? Action ? Exception ? Result.

Each filter intercepts a specific phase of the MVC pipeline for cross-cutting behaviors.

Quick Summary: Filter execution order: global filters → controller filters → action filters. Within each scope: Authorization → Resource → Action → Result → Exception. Action Filters run before and after the action. Resource Filters can short-circuit before model binding. Exception Filters catch unhandled exceptions from the action. IOrderedFilter lets you control order within the same scope.
Q49:

What is the difference between Authentication and Authorization in ASP.NET Core?

Mid

Answer

Authentication identifies the user. Authorization decides what the user can access. ASP.NET Core uses modular auth handlers and policy-based authorization.

Quick Summary: Authentication answers "who are you?" — it validates the identity (cookie, JWT, API key) and populates HttpContext.User. Authorization answers "can you do this?" — it checks the authenticated user's claims against policies and requirements ([Authorize], [AllowAnonymous]). Authentication must run before Authorization in the pipeline.
Q50:

What is Razor Layout Hierarchy and how does nested view rendering work?

Mid

Answer

Views use a layout, layouts can inherit from parent layouts, and sections flow through the rendering chain to generate multi-layer UI structures.

Quick Summary: A layout wraps content views. Child views use @{Layout = "_Layout";} or inherit from _ViewStart.cshtml. Nested layouts work hierarchically — a child layout sets its own Layout to a parent layout. Each level calls @RenderBody() to include its child's content. The rendering is inside-out: innermost view renders first, then each layout wraps it.
Q51:

How does ASP.NET Core support Localization and Globalization?

Mid

Answer

ASP.NET Core supports culture-specific formatting, resource-based translations, and dynamic culture selection via query, cookie, header, or route.

Quick Summary: ASP.NET Core localizes via IStringLocalizer (translates strings), IHtmlLocalizer (HTML-safe strings), and resource files (.resx). The RequestLocalizationMiddleware detects the user's preferred culture from URL, cookies, or Accept-Language headers and sets CultureInfo.CurrentCulture. Use [Route("{culture}/...")] for URL-based language switching.
Q52:

Explain how Dependency Injection Scopes affect Views, Controllers, and Middleware differently.

Mid

Answer

Controllers use scoped services per request. Views should avoid heavy scoped logic. Middleware is singleton-like and must not directly depend on scoped services.

Quick Summary: Controller: Scoped DI matches the request lifetime — one controller instance per request. Middleware: can be Singleton (defined at startup) or inline lambda. Razor Views: can inject Scoped services directly. The critical rule: never inject a Scoped service into a Singleton — the Scoped service lives longer than its intended request lifetime, causing data leakage between requests.
Q53:

How does the Razor Compilation System work and what optimizations exist?

Mid

Answer

Razor parses .cshtml ? generates C# ? compiles to assembly ? caches output. Precompilation improves startup, reduces CPU usage, and enhances performance.

Quick Summary: In production, Razor views are precompiled to C# during dotnet publish — shipped as DLLs, no .cshtml files needed. View compilation uses Roslyn. With Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation in development, Razor recompiles views on change without app restart. The RazorPage base class and generated Execute() method render HTML by writing to a TextWriter.
Q54:

What are Page Filters in Razor Pages and how do they differ from MVC Filters?

Mid

Answer

Page Filters wrap Razor Page lifecycle (handler selection, binding, execution). They are lighter and page-focused, unlike MVC-wide action filters.

Quick Summary: Page Filters in Razor Pages are the equivalent of MVC Action Filters but for page handler methods. They implement IPageFilter or IAsyncPageFilter. They run around OnGet, OnPost, etc. Unlike MVC Filters (which can be global across controllers), Page Filters apply to specific Razor Pages and integrate with the Razor Pages execution model.
Q55:

What is the View Engine pipeline and how do multiple view engines coexist?

Mid

Answer

View engines resolve, compile, and render views. Multiple engines coexist by searching in order; the first match handles rendering.

Quick Summary: The View Engine pipeline: IViewEngine.FindView() searches registered view engines in order for the view by name and controller context. Each engine (RazorViewEngine, etc.) returns a ViewEngineResult. The first found view is compiled and returned. Custom view engines implement IViewEngine and are registered in MVC options before or after the default Razor engine.
Q56:

Explain Application Parts and why large apps rely on them.

Mid

Answer

Application Parts allow MVC to discover controllers, views, and tag helpers from multiple assemblies, enabling plugin-based modular architectures.

Quick Summary: Application Parts are components that contribute controllers, views, tag helpers, and other features to an ASP.NET Core app. By default, the main assembly is an Application Part. Add external assemblies as Application Parts (ApplicationPartManager.AddApplicationPart) to enable modular apps where features come from separate class libraries loaded dynamically.
Q57:

What is Antiforgery protection and how does it work internally?

Mid

Answer

CSRF protection uses synchronized cookie + request tokens. Both must match for valid POST. ASP.NET Core auto-validates and secures tokens.

Quick Summary: The antiforgery system generates two tokens: a server-signed token embedded in the form (hidden field) and a cookie. Both are tied to the current user session. On POST, ASP.NET Core reads both, verifies they match the user's session, and validates the HMAC signature. A cross-site attacker can't forge a matching pair without access to the user's cookies and the signing key.
Q58:

Why does ASP.NET Core enforce asynchronous patterns everywhere?

Mid

Answer

Async frees threads, increases concurrency, prevents starvation, avoids deadlocks, and enables high-throughput Kestrel performance.

Quick Summary: I/O operations (database, file system, network calls) are slow — milliseconds to seconds. Synchronous I/O blocks the thread completely during that time. ASP.NET Core is designed to handle many concurrent requests with limited threads. Async I/O releases the thread to handle other requests while waiting, dramatically increasing request throughput with the same thread count.
Q59:

How do performance tuning strategies differ for Razor Pages vs MVC?

Mid

Answer

Razor Pages reduce routing overhead and grouping complexity. MVC handles large complex routing better. Both benefit from caching, precompiled views, and minimized layout nesting.

Quick Summary: Razor Pages bundle controller logic and view in one file — easier to optimize per-page. MVC separates controller from view — reuse opportunities but more complexity. Razor Pages benefit more from output caching at the page level. Both share the same middleware, authentication, and DI infrastructure. Razor Pages are simpler for page-centric flows; MVC scales better for complex APIs.
Q60:

What is the role of Metadata Providers in MVC?

Mid

Answer

Metadata Providers supply display names, formatting rules, validation metadata, and UI hints for binding, validation, scaffolding, and rendering.

Quick Summary: Metadata providers (IDisplayMetadataProvider, IValidationMetadataProvider) supply metadata about model properties to MVC — display names, validation messages, data type hints. They're used by Razor Tag Helpers and HTML Helpers to generate form fields with correct labels and error messages. Custom providers let you centralize display logic instead of scattering DataAnnotations everywhere.
Q61:

Explain Razor Runtime Rendering Optimizations.

Mid

Answer

Razor uses buffered output, strategic flush points, efficient writers, and pre-encoded content to reduce allocations and improve rendering speed.

Quick Summary: At render time, Razor views write HTML into an HtmlTextWriter via buffered string concatenation. Optimization: precompiled views skip the compilation step; output caching at the IOutputCache level caches rendered HTML. TagHelpers and IHtmlHelper are designed to minimize string allocations. For high-throughput pages, avoid complex layouts and deep partial view nesting.
Q62:

What is ASP.NET Core and why was it created?

Mid

Answer

ASP.NET Core is a modern, cross-platform, high-performance framework for building web applications. It was created to replace the heavy, Windows-only ASP.NET Framework. ASP.NET Core offers modularity, built-in DI, a redesigned hosting model, lightweight runtime, and full Linux + container support.

Quick Summary: ASP.NET Core is the cross-platform, open-source successor to ASP.NET Framework. It runs on Linux, macOS, and Windows — enabling container deployments. It's built with performance as a priority (one of the fastest web frameworks benchmarked), cloud-native design (12-factor app compatible), and a clean, modular pipeline replacing legacy HTTP handlers and modules.
Q63:

Explain the ASP.NET Core hosting model (Host Builder, Kestrel, Startup flow).

Mid

Answer

The hosting model uses a unified Host that configures DI, logging, configuration, server startup, environment settings, and middleware pipeline creation. It initializes Kestrel, loads configuration, builds services, and finally runs the HTTP pipeline.

Quick Summary: WebApplication.CreateBuilder() sets up the Generic Host. Builder.Services adds DI registrations. builder.Build() creates the WebApplication. Then middleware is added (app.UseAuthentication(), app.MapControllers(), etc.). app.Run() starts Kestrel listening. In .NET 6+ this is all in Program.cs — no Startup.cs required.
Q64:

What is Kestrel and why does ASP.NET Core use it?

Mid

Answer

Kestrel is a fast, cross-platform, event-driven web server optimized for async I/O. It offers superior throughput, supports reverse proxies, and provides full control over the request pipeline. It is the default server in ASP.NET Core.

Quick Summary: Kestrel is ASP.NET Core's built-in HTTP server written in managed C# — fast, cross-platform, and doesn't require IIS. It handles HTTP/1.1, HTTP/2, and HTTP/3 natively. In production, nginx or IIS typically sits in front as a reverse proxy for TLS termination and load balancing. Kestrel is always the actual HTTP server handling ASP.NET Core traffic.
Q65:

Explain Middleware and the ASP.NET Core Request Pipeline.

Mid

Answer

Middleware are ordered components processing every HTTP request sequentially. Each middleware can inspect/modify requests and responses, call the next middleware, or short-circuit the pipeline. The pipeline controls routing, authentication, logging, static files, and more.

Quick Summary: The middleware pipeline is a series of delegates chained together. Each middleware receives the HttpContext, does its work, and optionally calls next() to pass to the next middleware. The pipeline builds up in Program.cs. It runs forward through all middlewares on request, and backward (through finally/response-writing middlewares) on the way back.
Q66:

Why does middleware order matter in ASP.NET Core?

Mid

Answer

Middleware executes in the order registered. Incorrect ordering may break authentication, routing, exception handling, and endpoint execution. ASP.NET Core gives full control to developers and does not auto-correct middleware ordering.

Quick Summary: Middleware is processed in the exact order it's added. Exception handling must come first to catch errors from all subsequent middleware. HTTPS redirection before authorization. Static files before routing (to short-circuit static requests). Authentication before authorization. Putting middleware in the wrong order causes bugs that only appear in production scenarios.
Q67:

What is Dependency Injection in ASP.NET Core and why is it built-in?

Mid

Answer

ASP.NET Core includes a built-in DI container for service registration, lifetime management, and constructor injection. It enables cleaner architecture, testability, and decoupling across the entire framework.

Quick Summary: Rather than instantiating dependencies manually (new Service()), ASP.NET Core's built-in DI container injects them automatically based on constructor parameters. This enables loose coupling (depend on interfaces), easier testing (inject mocks), and proper lifecycle management. It's built-in so every framework feature (controllers, middleware, Razor Pages) supports it natively.
Q68:

Explain Transient, Scoped, and Singleton lifetimes.

Mid

Answer

Transient: new instance each request.
Scoped: one instance per HTTP request.
Singleton: one instance for entire app lifetime. Choosing correct lifetime is crucial to avoid memory leaks and race conditions.

Quick Summary: Transient: new instance every injection — good for stateless services like email senders. Scoped: one instance per HTTP request — DbContext is the canonical example (one per request, shares a transaction). Singleton: one shared instance for the entire app lifetime — good for thread-safe, stateless services like IHttpClientFactory or caches.
Q69:

How does ASP.NET Core Configuration system work?

Mid

Answer

Configuration is layered: JSON files, environment variables, user secrets, key vaults, in-memory providers. Each source overrides the previous. Supports binding to objects, reload-on-change, and environment-based settings.

Quick Summary: Configuration is layered and merged: appsettings.json (base) → appsettings.Development.json (environment override) → environment variables → command-line. Later sources win. Access via IConfiguration["Key"] or GetSection(). Bind entire sections to typed POCOs with services.Configure(config.GetSection("Section")) for strongly-typed access.
Q70:

Explain IOptions, IOptionsSnapshot, and IOptionsMonitor.

Mid

Answer

IOptions: One-time config snapshot at startup.
IOptionsSnapshot: Reloaded per request.
IOptionsMonitor: Real-time change tracking + callbacks. Used for dynamic config updates.

Quick Summary: IOptions: singleton, reads config once at startup, doesn't see runtime changes. IOptionsSnapshot: scoped, re-reads config each request — picks up changes between requests. IOptionsMonitor: singleton with change notification — OnChange() fires immediately when config files change. Use Monitor for services that need live config updates.
Q71:

What is Routing in ASP.NET Core and how does Endpoint Routing work?

Mid

Answer

Routing maps URLs to endpoints (controllers/pages). Endpoint Routing performs early route matching and delays execution until UseEndpoints(). It allows metadata-driven policies (auth, CORS) and improves performance.

Quick Summary: Routing matches HTTP requests to endpoints. Endpoint Routing (current) separates matching (UseRouting) from execution (UseEndpoints/MapControllers). This allows middleware between matching and execution to use route data — like authorization middleware reading route metadata. Attribute routing ([Route], [HttpGet]) gives explicit control per action.
Q72:

Compare Conventional Routing vs Attribute Routing.

Mid

Answer

Conventional routing: Central route patterns. Good for large MVC apps.
Attribute routing: Defined on actions. Best for APIs and unique routes.

Quick Summary: Conventional routing: one route template for many controllers (app.MapControllerRoute("default", "{controller=Home}/{action=Index}")). Easy for consistent CRUD apps. Attribute routing: each controller/action has its own explicit route. More granular control, better for REST APIs with custom URL structures. Most APIs use attribute routing.
Q73:

What is Model Binding in ASP.NET Core?

Mid

Answer

Model binding converts HTTP request data (query, form, route, headers) into .NET objects. Supports type conversion, collections, nested models, and custom binders.

Quick Summary: Model binding reads request data (JSON body, form fields, route segments, query string) and maps it to action parameters. An action public IActionResult Create(CreateUserDto dto) automatically gets dto populated from the request JSON body. No manual request.Body reading required. Customizable with [FromBody], [FromQuery], [FromRoute] attributes.
Q74:

Explain Model Validation and how it works.

Mid

Answer

Runs after binding and before action execution. Uses data annotations, custom validation attributes, and IValidatableObject. Validation results go into ModelState and must be checked before using the data.

Quick Summary: Data annotations on model properties define rules: [Required], [StringLength(100)], [Range(1,100)], [EmailAddress]. ASP.NET Core runs these after binding and populates ModelState. if (!ModelState.IsValid) return BadRequest(ModelState) returns 400 with validation errors. Custom attributes inherit ValidationAttribute for complex rules.
Q75:

What are Filters in ASP.NET Core MVC and why are they important?

Mid

Answer

Filters run at specific pipeline stages: authorization, resource, action, exception, result. Used for logging, caching, security, and cross-cutting concerns.

Quick Summary: Filters inject behavior into the MVC pipeline at specific stages. Use Action Filters to log parameters, validate custom headers, or measure execution time. Use Authorization Filters for custom auth checks. Use Exception Filters to format error responses consistently per API. Filters are more MVC-aware than middleware — they receive action context and model state.
Q76:

What are Razor Views and why are they used?

Mid

Answer

Razor is a lightweight HTML + C# templating engine. It avoids WebForms complexity and supports clean, fast, server-side rendering with async support and strong tooling.

Quick Summary: Razor Views are .cshtml files that mix HTML with C# via Razor syntax (@Model, @foreach, @if). They're compiled to C# classes by the Razor compiler. They receive a strongly-typed @model declared at the top. The controller renders a view with View(model) after processing a request. They separate presentation from logic.
Q77:

Explain Layouts, Partial Views, and View Components.

Mid

Answer

Layouts: Master page structure.
Partial Views: Reusable HTML fragments.
View Components: Reusable UI with C# logic + view. Ideal for widgets/dashboards.

Quick Summary: _Layout.cshtml is the shared wrapper view — header, nav, footer, common CSS/JS. Partial Views are re-rendered HTML fragments — . ViewComponents are mini-MVC features: InvokeAsync() runs logic (queries DB, injects services), then renders a view. Use ViewComponents when a UI widget has its own data requirements.
Q78:

What are Tag Helpers and why are they preferred?

Mid

Answer

Tag Helpers enable server-side logic using HTML-like syntax. They improve readability, provide IntelliSense, enforce validation, and reduce C# noise in Razor.

Quick Summary: Tag Helpers look like HTML attributes but run server-side:
generates the correct action URL. They're type-safe, support IntelliSense, and are easier to read than @Html.BeginForm() HTML helpers. Built-in Tag Helpers handle form generation, input types, validation messages, links, and more.
Q79:

What is TempData and how is it different from ViewData and ViewBag?

Mid

Answer

ViewData / ViewBag: For same-request data.
TempData: Stores data across redirects and is removed after read. Backed by cookies or session.

Quick Summary: TempData stores data for the next request only — redirected data. Set before redirect: TempData["Message"] = "Saved!"; read after redirect. TempData uses cookie or session storage behind the scenes. ViewData: dictionary for current request, controller → view. ViewBag: dynamic version of ViewData. Neither survives a redirect.
Q80:

What is Anti-Forgery and why is it required in ASP.NET Core?

Mid

Answer

Anti-forgery tokens prevent CSRF attacks by validating a cookie token + form token pair. ASP.NET Core automatically validates tokens for unsafe HTTP verbs like POST.

Quick Summary: CSRF attacks forge requests from a malicious site using the victim's authenticated session. Anti-forgery prevents this by requiring a secret token only the legitimate server and browser share. ASP.NET Core validates the token on every form POST. Razor's tag helper adds it automatically. APIs using JWT tokens in headers don't need anti-forgery (no cookie auth).
Q81:

How does ASP.NET Core handle static files and why is the middleware special?

Mid

Answer

Static Files Middleware serves files directly from wwwroot with no MVC involvement, improving performance. Must be placed early to avoid being processed by routing or MVC.

Quick Summary: UseStaticFiles() middleware intercepts requests matching files in wwwroot (CSS, JS, images) before routing. It serves them directly with appropriate Content-Type and ETag/Cache-Control headers. It must come before UseRouting() and before any auth middleware — static assets are public and should be served without auth checks.
Q82:

Explain the ASP.NET Core hosting model (Host Builder + Kestrel + Startup flow).

Senior

Answer

The hosting model uses a Generic Host that configures DI, logging, configuration, environment settings, and Kestrel. Startup constructs middleware pipeline and endpoint routing. The flow is: Host ? Kestrel ? Middleware ? Routing ? Endpoint.

Quick Summary: The Generic Host (IHostBuilder) provides a unified hosting model for web apps, workers, console apps, and Windows services. It handles DI, configuration, logging, and application lifetime centrally. The older Web Host (IWebHostBuilder) was web-only. Generic Host replaced it in .NET 3.1+ as the standard for all .NET apps.
Q83:

What is Kestrel and why does ASP.NET Core use it?

Senior

Answer

Kestrel is a high-performance cross-platform server optimized for asynchronous I/O. ASP.NET Core uses it because it offers superior throughput, low memory overhead, full platform portability, and seamless integration behind reverse proxies like Nginx/IIS.

Quick Summary: Kestrel handles raw HTTP/HTTPS connections and processes requests fully within the .NET process. It's fast, cross-platform, and supports HTTP/2 and HTTP/3. Without IIS or nginx in front, Kestrel handles everything. In production, a reverse proxy handles TLS, rate limiting, and load balancing while forwarding HTTP to Kestrel internally.
Q84:

Explain Middleware and the purpose of the ASP.NET Core Request Pipeline.

Senior

Answer

Middleware components execute sequentially for every request. Each can inspect, modify, or short-circuit the pipeline. This modular pipeline replaces old HTTP modules/handlers and provides full control over request flow.

Quick Summary: Each middleware is a delegate that wraps the rest of the pipeline. When you call app.Use(async (context, next) => { ... await next(context); }), you're adding a step. Each middleware can short-circuit (return without calling next) or continue. The order is critical — authentication must come before authorization; routing before endpoint execution.
Q85:

What is Dependency Injection in ASP.NET Core and why is it built-in?

Senior

Answer

ASP.NET Core includes a first-class DI container used across the entire framework: controllers, middleware, services. It promotes testable, modular, and maintainable architecture without external frameworks.

Quick Summary: ASP.NET Core's built-in DI removes the need for external IoC containers for most use cases. It supports constructor injection for controllers, services, middleware, and Razor Pages. Registering abstractions and concrete implementations enables runtime swap of implementations — critical for unit testing with mocks.
Q86:

Explain DI lifetimes: Transient, Scoped, Singleton.

Senior

Answer

Transient: New instance each request.
Scoped: One instance per HTTP request.
Singleton: One instance for entire app lifetime.

Wrong lifetimes cause concurrency bugs, memory leaks, or stale state.

Quick Summary: Transient: fresh instance each injection — good for lightweight, stateless services. Scoped: single instance per HTTP request — EF Core DbContext is the classic example. Singleton: one shared instance for the app's lifetime — should be thread-safe. Never capture Scoped or Transient services in a Singleton — they'll be shared across all requests incorrectly.
Q87:

How does Configuration work in ASP.NET Core?

Senior

Answer

The configuration system merges layered sources: appsettings.json, environment-specific JSON, env variables, command-line args, user secrets, and external sources. Binding and hot-reload supported.

Quick Summary: Configuration providers layer their values: appsettings.json base → environment-specific JSON → environment variables → command-line args. Each layer can override previous ones. Providers implement IConfigurationProvider. You can add custom providers (database, Vault, etcd) by calling builder.Configuration.Add(yourProvider).
Q88:

What is the purpose of IOptions, IOptionsSnapshot, and IOptionsMonitor?

Senior

Answer

IOptions: Singleton config.
IOptionsSnapshot: Reload per request.
IOptionsMonitor: Real-time config with change notifications.

Quick Summary: IOptions is singleton — reads config at startup. IOptionsSnapshot is scoped — reflects config changes between requests (requires file-based config with reloadOnChange: true). IOptionsMonitor is singleton with a reactive change callback — use it in singletons that need to react to configuration changes without restarting.
Q89:

What is Routing in ASP.NET Core?

Senior

Answer

Endpoint Routing maps URLs to endpoints. It performs early URL matching, supports metadata, improves performance with route tables, and centralizes routing logic.

Quick Summary: Routing maps URL patterns to endpoint handlers. UseRouting() does the matching. UseEndpoints() / MapControllers() / MapGet() defines and executes the endpoints. Attribute routing ([Route("api/[controller]")]) gives precise URL control per action. Route constraints ({id:int:min(1)}) enforce parameter types and values at routing time.
Q90:

What is Model Validation and how does it work?

Senior

Answer

Validation runs after binding and populates ModelState with errors. Action logic executes only after validation passes. Supports Data Annotations, custom validators, and IValidatableObject.

Quick Summary: Data annotations validate model properties after binding. [Required] prevents nulls/empties; [StringLength] limits character count; [Range] checks numeric bounds. ModelState.IsValid tells you if all passed. Return 400 with ModelState if invalid. For complex rules spanning multiple fields, implement IValidatableObject.Validate() on the model class.
Q91:

What are Filters and why are they important?

Senior

Answer

Filters run at specific pipeline stages: Authorization, Resource, Action, Exception, and Result filters. They implement cross-cutting concerns like logging, caching, or auditing.

Quick Summary: Filters are pipeline hooks for cross-cutting concerns. Authorization Filters run first and can short-circuit unauthenticated requests. Action Filters run before/after the action — log parameters, validate headers. Result Filters wrap result execution — modify output. Exception Filters handle unhandled exceptions from actions. All can be scoped globally, per-controller, or per-action.
Q92:

Explain Layouts, Partial Views, and View Components.

Senior

Answer

Layouts: Master UI shell.
Partial Views: Shared HTML fragments.
View Components: Reusable components with logic + view.

Quick Summary: _Layout.cshtml defines the shared page structure (header, nav, CSS imports). Views call @RenderBody() in the layout to inject their content. Partial Views: @Html.Partial("_Card", model) or tag helper — stateless HTML fragment. ViewComponents: @await Component.InvokeAsync("MyWidget") — runs logic and renders a sub-view with its own DI and async support.
Q93:

What is TempData and how is it different from ViewData/ViewBag?

Senior

Answer

ViewData/ViewBag: For same request only.
TempData: Persisted across redirects using cookies or session. Ideal for one-time messages.

Quick Summary: TempData survives exactly one redirect. Set it before RedirectToAction(); read it in the destination action or view. ViewData is a dictionary — controller sets it, view reads it within one request. ViewBag is dynamic syntax over ViewData (ViewBag.Title = "X" is ViewData["Title"] = "X"). TempData uses cookie or session; the others don't persist.
Q94:

Explain the ASP.NET Core hosting model (Host Builder + Kestrel + Startup flow).

Senior

Answer

ASP.NET Core uses a unified Host that manages configuration, logging, DI, environment, and pipeline. The flow:

  • Host initializes runtime and services
  • Kestrel web server starts
  • Configuration sources load
  • Services added to DI
  • Middleware pipeline built
  • The app starts listening for HTTP requests

The unified model gives fine-grained control of every system layer.

Quick Summary: The Generic Host handles all .NET app types — web, worker, console, Windows service. Builder.Services registers dependencies; builder.Configuration reads config sources; builder.Logging adds log providers. Build() creates the host; Run() starts it. WebApplication (minimal API) wraps this in .NET 6+ with an even simpler API.
Q95:

Explain Middleware and the ASP.NET Core Request Pipeline.

Senior

Answer

Middleware are sequential components that inspect, transform, route, or short-circuit HTTP requests. Each middleware can:

  • Read request
  • Modify response
  • Call next middleware
  • Handle the response entirely

The pipeline is flexible, efficient, and replaces legacy HTTP modules/handlers.

Quick Summary: Request enters → runs through middleware in order: exception handler → HSTS → static files → routing → auth → authorization → endpoint. Response returns through middlewares in reverse. Each middleware calls next() to continue or returns early to short-circuit. The pipeline is built in Program.cs with app.Use*() methods.
Q96:

What is Dependency Injection in ASP.NET Core and why is it built-in?

Senior

Answer

ASP.NET Core includes a built-in DI container to unify object creation, lifecycle management, and dependency resolution. DI improves maintainability, testing, modularity, and supports the framework's extensible design.

Quick Summary: ASP.NET Core's container (IServiceCollection) enables constructor injection everywhere — controllers, Razor Pages, middleware, ViewComponents. Register via services.AddScoped(). The framework resolves the dependency graph automatically at runtime. This eliminates manual new() calls and enables testability by swapping implementations.
Q97:

What is Configuration in ASP.NET Core and how does it work?

Senior

Answer

ASP.NET Core configuration is hierarchical and supports multiple providers:

  • appsettings.json
  • Environment-specific files
  • Env variables
  • Command-line arguments
  • Secrets / Key Vault

Values bind to strongly-typed classes and support reload-on-change.

Quick Summary: Configuration reads from multiple sources layered: JSON → environment variables → command-line → secrets. Each source can override previous values. IConfiguration is the unified interface. Bind sections to strongly-typed POCOs with services.Configure(config.GetSection("MySection")) for type-safe access throughout the app.
Q98:

What is the purpose of IOptions, IOptionsSnapshot, and IOptionsMonitor?

Senior

Answer

  • IOptions: Singleton configuration, loaded once.
  • IOptionsSnapshot: Per-request config, refreshed each request.
  • IOptionsMonitor: Live config with change notifications.
Quick Summary: Three options interfaces for different scenarios: IOptions never changes after startup (singleton). IOptionsSnapshot re-reads per request — good for config files with reloadOnChange: true. IOptionsMonitor notifies subscribers immediately when config changes — best for singletons that need live updates without restart.
Q99:

What is Model Binding?

Senior

Answer

Model Binding converts HTTP inputs (query, route, form, body, headers) into strongly-typed .NET objects. It abstracts away manual parsing.

Quick Summary: Model binding maps HTTP request data to action parameters automatically. ASP.NET Core reads [FromBody] from the request body (JSON), [FromRoute] from route segments, [FromQuery] from query string, [FromForm] from form data. Without explicit attributes, it uses default sources based on parameter type (complex types default to body, simple types to query).
Q100:

What are Filters and why are they important?

Senior

Answer

Filters enable cross-cutting concerns such as logging, caching, authorization, and exception handling. Types include authorization, resource, action, exception, and result filters.

Quick Summary: Filters are AOP-style hooks. Authorization Filters gate access. Action Filters run business logic before/after action (logging, performance measurement). Result Filters modify responses (add headers, compress). Exception Filters catch unhandled action exceptions for consistent error formatting. Filters are more expressive than middleware for MVC-specific concerns.
Q101:

Explain Layouts, Partial Views, and View Components.

Senior

Answer

  • Layouts: Master templates for shared UI.
  • Partials: Reusable HTML fragments.
  • View Components: Encapsulated logic + view, ideal for widgets.
Quick Summary: Layout: _Layout.cshtml wraps views with shared chrome. Partial Views: reusable HTML fragments rendered inline with . ViewComponents: smart, self-contained widgets that run async logic (inject services, call DB) and render their own view — like a mini-controller. Best for dynamic sidebars, notification badges, and complex UI sections.
Q102:

What are Tag Helpers?

Senior

Answer

Tag Helpers enable server-side processing of HTML elements. They provide compile-time checking, IntelliSense, clean syntax, and strong typing.

Quick Summary: Tag Helpers process HTML elements server-side during view rendering. generates a correctly-named input with validation attributes. They look like plain HTML and work with HTML IntelliSense. Much cleaner than @Html.TextBoxFor(m => m.Email) HTML Helper syntax, which is C#-centric and harder to style.
Q103:

What is TempData and how is it different from ViewData/ViewBag?

Senior

Answer

ViewData/ViewBag: Per-request data.

TempData: Persists across redirects until consumed. Backed by cookies or session.

Quick Summary: TempData persists across a redirect — set before redirecting, read in destination. Useful for success/error messages after form submissions. ViewData: dictionary for current request (controller sets, view reads). ViewBag: dynamic property syntax over ViewData. TempData uses either cookie or session backend. All three are for controller-to-view communication.
Q104:

How does ASP.NET Core handle static files and why is middleware important?

Senior

Answer

The Static Files middleware serves CSS/JS/images directly without MVC involvement. It must be placed early in the pipeline to bypass unnecessary routing and processing.

Quick Summary: Static Files middleware intercepts matching file requests before routing and serves them directly from wwwroot — no controller, no auth required. It must be first in the pipeline so static assets (CSS, JS) are available to unauthenticated users. Without it, every static file request would go through the full MVC pipeline unnecessarily.
Q105:

Difference between Generic Host and Web Host.

Senior

Answer

Generic Host is the unified hosting model supporting all app types (web, workers, gRPC). Web Host was only for web apps. Generic Host centralizes DI, logging, config, and enables multi-service hosting.

Quick Summary: Generic Host is the modern, unified host for all .NET app types — web, worker services, console apps. Web Host was the original ASP.NET Core-specific host, now superseded. In .NET 6+, WebApplication.CreateBuilder() uses Generic Host internally. Both support DI, configuration, and logging — but Generic Host is the standard going forward.
Q106:

Explain ASP.NET Core Application Lifetime events.

Senior

Answer

Lifetime events:

  • ApplicationStarted
  • ApplicationStopping
  • ApplicationStopped

They allow warm-ups, cache initialization, graceful shutdowns, and log flushing.

Quick Summary: IHostApplicationLifetime provides hooks: ApplicationStarted fires when the host is ready (warm caches, connect to message brokers). ApplicationStopping fires when shutdown is requested but before it completes (drain connections, stop background work). ApplicationStopped fires when everything is done. Inject it into any service that needs lifecycle awareness.
Q107:

What is Web Root vs Content Root in ASP.NET Core?

Senior

Answer

Content Root: Base path for code, views, and config files.

Web Root: Public folder (wwwroot) exposed to the web for static files.

This separation prevents accidental exposure of sensitive project files.

Quick Summary: Content Root is the app's home directory — contains appsettings.json, Views, Program.cs output. Web Root (wwwroot by default) is the public directory served to browsers — CSS, JS, images. Separating them ensures the app's source, configs, and secrets are never accidentally served as static files by the Static Files middleware.
Q108:

What happens inside the CLR from compilation to execution?

Senior

Answer

The CLR pipeline includes Roslyn compilation to IL, metadata creation, IL loading, verification, JIT compilation, and optimized native execution through tiered compilation and RyuJIT. Execution runs under GC, exception handling, and runtime type safety. Supports JIT, AOT, ReadyToRun, and NativeAOT modes.

Quick Summary: When you write C#, Roslyn compiles it to IL (Intermediate Language), stored in a .dll assembly. The CLR loads the assembly, verifies the IL, and the JIT compiler converts it to native machine code on first execution. The GC manages memory automatically — allocating on the managed heap and reclaiming unreachable objects.
Q109:

Explain the .NET Memory Model and its effect on multi-threading.

Expert

Answer

The .NET Memory Model defines visibility, ordering, and synchronization rules. It allows reordering unless blocked by barriers. Volatile improves visibility; Interlocked and lock introduce memory fences. Handles tearing, cache coherency, ABA issues, and provides relaxed consistency similar but less strict than Java.'s model.

Quick Summary: The .NET memory model defines ordering guarantees between threads. Without synchronization, the CPU or compiler can reorder reads and writes — one thread might see stale values. lock adds full memory barriers (prevents reordering). volatile prevents caching. Interlocked provides atomic operations. Correct multi-threaded code needs explicit synchronization.
Q110:

How does CLR allocate memory for value types vs reference types?

Expert

Answer

Value types are stored inline (stack or within objects). Reference types always reside on the heap. Boxing allocates objects with headers and method table pointers. Inline struct fields avoid indirection, improving cache locality and performance.

Quick Summary: Value types (int, struct) on the stack are allocated in the current method's stack frame — no GC overhead. On the heap (as fields of a class), they're embedded directly in the object. Reference types always go on the managed heap with a GC header. Value types in arrays/objects are inlined; reference types store a pointer.
Q111:

Describe the internal layout of a .NET object.

Expert

Answer

A .NET object layout includes: Method Table pointer, Sync Block index, aligned fields with padding, and metadata references. The Method Table stores vtable, type hierarchy, and GC tracking info.

Quick Summary: Every .NET object has an object header (8 bytes on 64-bit): a SyncBlock index (for lock and GetHashCode) and a Method Table pointer (links to type info, vtable for virtual dispatch). After the header come the object's fields. This overhead means even a small object costs more memory than its fields alone.
Q112:

Explain GC Generations, LOH, and POH behavior.

Expert

Answer

Gen0 handles short-lived objects, Gen1 buffers promotions, and Gen2 manages long-lived objects. LOH (>=85 KB) is collected only during full GC. POH isolates pinned objects to avoid LOH fragmentation. GC modes include server, workstation, and background.

Quick Summary: Gen0 collects short-lived objects — collected frequently, fast. Gen1 is a buffer between Gen0 and Gen2. Gen2 collects long-lived objects — full GC, expensive. LOH (Large Object Heap, objects >= 85KB) collects during Gen2 and isn't compacted by default (fragmentation risk). POH (Pinned Object Heap, .NET 5+) stores objects pinned for native interop safely.
Q113:

What is Tiered Compilation in .NET and why is it important?

Expert

Answer

Tier 0 generates fast unoptimized code for quick startup; Tier 1 recompiles hot paths with optimizations. Tiered PGO enhances long-running performance. Together they balance startup speed and runtime throughput.

Quick Summary: Tiered compilation runs code at Tier 0 (minimal optimization, fast startup) first. After a method is called N times (hot path), it's recompiled at Tier 1 with full JIT optimizations. With PGO (Profile-Guided Optimization) in .NET 6+, Tier 1 uses actual runtime profile data to make even better optimization decisions.
Q114:

Difference between lock, Monitor, Mutex, Semaphore, SpinLock, and RWLockSlim.

Expert

Answer

lock/Monitor for lightweight mutual exclusion; Mutex for cross-process locks; Semaphore limits concurrency; SpinLock for low-contention busy waits; ReaderWriterLockSlim for read-heavy workloads. Each has different contention and fairness characteristics.

Quick Summary: lock/Monitor: process-local, reentrant, lightweight. Mutex: cross-process named mutex, heavier. Semaphore: limits N concurrent threads. SpinLock: busy-waits instead of blocking — zero context-switch overhead for very short critical sections. ReaderWriterLockSlim: multiple concurrent readers, exclusive write access — great for read-heavy shared data.
Q115:

How does async/await work internally?

Expert

Answer

Compiler rewrites async methods into state machines. Await posts continuations to SynchronizationContext or thread pool. Tasks represent operations and manage completion, cancellation, and exceptions. Avoid context capture for performance.

Quick Summary: The compiler transforms an async method into a state machine struct. Each await point is a state. When the awaited task completes, the continuation is posted to the captured SynchronizationContext (or thread pool). The thread is released during the await — no blocking. The async state machine struct avoids heap allocation for common cases.
Q116:

Explain String Interning and its risks.

Expert

Answer

Intern pool stores unique literals for lifetime of the process. Reduces duplication but increases memory pressure. Interning user input is dangerous due to unbounded growth.

Quick Summary: String interning stores one shared instance per unique string literal. string.Intern() can intern any string. Interned strings live in a process-wide pool and are never GC'd. Risk: interning dynamic strings (user input, random data) fills the intern pool permanently, causing memory growth that GC can't reclaim.
Q117:

Difference between Reflection, Reflection.Emit, Expression Trees, and Source Generators.

Expert

Answer

  • Reflection: runtime inspection, slow
  • Emit: dynamic IL generation
  • Expression Trees: compile to delegates for fast execution
  • Source Generators: compile-time code generation using Roslyn
Quick Summary: Reflection: runtime type inspection and invocation — slow, bypasses compile-time safety. Reflection.Emit: generates IL at runtime — used in proxies and ORMs. Expression Trees: represent code as data structures, compiled to delegates — used in LINQ providers. Source Generators: generate code at compile time — zero runtime cost, the modern preferred approach.
Q118:

How does .NET ThreadPool schedule work?

Expert

Answer

ThreadPool uses global/per-thread queues, work stealing, and hill-climbing to adjust worker counts. Long-running tasks should use LongRunning to avoid blocking worker threads.

Quick Summary: The ThreadPool maintains a global work-stealing queue and per-thread local queues. Threads steal from each other when idle. A hill-climbing algorithm adjusts thread count based on throughput (measured every ~15ms). For long-running CPU work (> ~500ms), use TaskCreationOptions.LongRunning to get a dedicated non-pool thread.
Q119:

Explain delegate types and internal representation.

Expert

Answer

Delegates may be open/closed static or instance methods. Multicast delegates contain invocation lists. Closures create hidden classes. Invocation chain length affects performance.

Quick Summary: A delegate stores a method pointer and a target instance (null for static methods). Lambdas that capture variables create a hidden compiler-generated closure class. Multicast delegates maintain an array of delegate instances — invocation iterates the array. The Invoke method calls them in order; exceptions in one delegate don't stop others unless you handle it manually.
Q120:

What is the role of Roslyn?

Expert

Answer

Roslyn provides syntax trees, semantic models, analyzers, refactoring, and code generation. It is compiler-as-a-service, powering tooling and source generators.

Quick Summary: Roslyn is the C# and VB compiler exposed as an API. It provides parse trees, semantic models, diagnostics, and code fixes that power Visual Studio IntelliSense, analyzers, and code generators. Source Generators hook into Roslyn to inspect your code at compile time and generate additional C# files before compilation finishes.
Q121:

Explain covariance and contravariance deeply.

Expert

Answer

Covariance (out) allows substituting derived for base. Contravariance (in) allows substituting base for derived. Applies to delegates, interfaces, and arrays (with runtime checks). Enables type-flexible APIs safely.

Quick Summary: Covariance (out T on IEnumerable): IEnumerable is assignable to IEnumerable — safe for read-only scenarios. Contravariance (in T on Action): Action is assignable to Action — safe for write-only scenarios. Applies to interfaces and delegates, not concrete classes. The in/out keywords express the variance direction.
Q122:

What are AppDomains and why removed in .NET Core?

Expert

Answer

AppDomains offered isolation and unloading but were heavy and complex. .NET Core replaced them with AssemblyLoadContext for lighter, flexible loading and unloading models.

Quick Summary: AppDomains in .NET Framework provided process-level isolation for loading and unloading assemblies independently. They were complex, platform-specific (Windows only), and rarely used correctly. .NET Core removed them for simplicity and cross-platform support. AssemblyLoadContext is the lightweight replacement for dynamic, isolated assembly loading in plugins.
Q123:

Explain IL, CIL, and MSIL.

Expert

Answer

IL, CIL, and MSIL refer to the same CPU-independent intermediate instruction set executed by the CLR before JIT compilation.

Quick Summary: IL (Intermediate Language), CIL (Common Intermediate Language), and MSIL (Microsoft IL) all refer to the same thing: the platform-independent bytecode that .NET compilers produce. CIL is the official ECMA standard name. MSIL is the old Microsoft name. IL is the everyday shorthand. The JIT converts IL to native machine code at runtime.
Q124:

Explain the CLR exception handling flow.

Expert

Answer

Exception handling involves stack unwinding, handler search, first/second chance exceptions, managed/unmanaged boundary transitions, and finally/fault execution. Throwing is expensive due to metadata lookup and stack analysis.

Quick Summary: When an exception is thrown, the CLR searches the call stack for a matching catch handler (walking up frame by frame). Finally blocks always run during unwinding. Unhandled exceptions terminate the process. First-chance exceptions are raised before any handler — useful for debuggers. The exception object captures the stack trace at throw time.
Q125:

What is metadata in assemblies and how does CLR use it?

Expert

Answer

Metadata includes type, method, field tables, attributes, signatures, and constraints. CLR uses it for JIT compilation, reflection, verification, and type loading.

Quick Summary: Assembly metadata describes every type, method, field, parameter, attribute, and generic constraint in the assembly. The CLR reads this during type loading to understand layout, method resolution, and reflection queries. It makes .NET assemblies self-describing — no header files needed, and tools like Visual Studio's IntelliSense read metadata at design time.
Q126:

Key performance traps senior engineers must avoid.

Expert

Answer

  • Excess allocations
  • Boxing
  • Heavy LINQ in hot paths
  • Lambdas capturing hidden allocations
  • Blocking async
  • Excessive locking
  • Exceptions for flow control
Quick Summary: Senior .NET performance traps: boxing value types in collections, sync-over-async (blocking .Result or .Wait()), capturing too-large closures in LINQ or lambdas, using string concatenation instead of StringBuilder in loops, large LOH allocations, excessive reflection, and not using Span or Memory for high-throughput buffer operations.
Q127:

What is ASP.NET Core and why was it created?

Expert

Answer

ASP.NET Core is a cross-platform, high-performance framework built to replace legacy ASP.NET limitations. It introduces modularity, DI, unified hosting, and lightweight request pipeline optimized for cloud and microservices.

Quick Summary: ASP.NET Core is the cross-platform, open-source rewrite of ASP.NET. It runs on Linux, macOS, and Windows. It's built for the cloud era — containerization-friendly, performance-optimized, and modular. The framework moved from IIS-coupled, Windows-only roots to a portable, middleware-based architecture with first-class support for Docker and microservices.
Q128:

Explain Middleware and the Request Pipeline.

Expert

Answer

Middleware executes sequentially and may process, modify, short-circuit, or delegate requests. Enables flexible, modular pipelines replacing old HttpModules/Handlers.

Quick Summary: The request pipeline is a chain of delegates (middleware). Each middleware can inspect and modify the HttpContext, call next() to continue, or short-circuit. Order is defined in Program.cs. The pipeline processes requests forward and responses backward — response-writing middleware sees the response after all downstream middleware have run.
Q129:

Why does middleware order matter?

Expert

Answer

Middleware runs exactly in registration order. Incorrect ordering breaks authentication, routing, exception handling, and static file behavior.

Quick Summary: Each middleware wraps subsequent ones. Wrong order causes real bugs: placing authorization before authentication means HttpContext.User is empty at auth check time. Placing routing after your endpoint handler means routes never match. Exception handling must wrap everything — placing it last means unhandled exceptions from early middleware aren't caught.
Q130:

Why is DI built-in to ASP.NET Core?

Expert

Answer

ASP.NET Core is designed around DI for clean structure, testability, separation of concerns, and consistent service creation across middleware, controllers, and background services.

Quick Summary: Built-in DI removes the need to manually instantiate services, manage their lifetimes, or pass dependencies through constructors manually. The container injects dependencies automatically. This enables: loose coupling (program to interfaces), testability (inject mocks), lifecycle management (scoped/transient/singleton), and framework integration (controllers get services injected automatically).
Q131:

Explain the ASP.NET Core configuration system.

Expert

Answer

Configuration is layered: appsettings.json, environment configs, secrets, environment variables, command-line args. Supports reload-on-change and strongly typed bindings.

Quick Summary: Multiple configuration sources layer together: JSON files, environment variables, User Secrets, Azure Key Vault. Values from later sources override earlier ones. IConfiguration provides the unified API. The system is composable — you can add custom providers for any config source. Strongly-typed options classes (IOptions) are the recommended way to consume configuration.
Q132:

What are IOptions, IOptionsSnapshot, and IOptionsMonitor?

Expert

Answer

IOptions: singleton read. Snapshot: per-request reload. Monitor: real-time change notifications for long-running services.

Quick Summary: Three interfaces for different needs: IOptions reads config once, never changes — use in singletons for static config. IOptionsSnapshot re-reads per request — use in scoped/transient services that need fresh config on every request. IOptionsMonitor reacts to live changes — use when the app must respond to config changes without restarting.
Q133:

What is Routing in ASP.NET Core?

Expert

Answer

Endpoint Routing maps URLs to endpoints with early matching, metadata support, and optimized execution. Supports attribute and conventional routes.

Quick Summary: Routing matches incoming requests to endpoints. Endpoint Routing (current model) matches routes in UseRouting() and executes them in UseEndpoints(). Convention routing: MapControllerRoute with a template. Attribute routing: [HttpGet("api/users/{id}")] on each action. Route parameters can have constraints: {id:int}, {name:alpha:length(5)}.
Q134:

How do Dependency Injection scopes affect Razor Views, Controllers, and Middleware differently?

Expert

Answer

Controllers use scoped services per request, Razor Views should avoid heavy scoped logic, and Middleware must avoid scoped services because middleware is created once and would turn scoped dependencies into singletons.

This scope behavior prevents state leakage, concurrency bugs, and lifecycle misalignment across pipeline components.

Quick Summary: Controllers receive Scoped services — fresh per request. Middleware registered as singletons (inline lambdas) must not capture Scoped services — inject them via IServiceProvider.CreateScope() instead. Razor Views can inject services via @inject and receive Scoped services correctly. The key rule: never store a Scoped service in a Singleton field.
Q135:

How does the Razor Compilation System work at runtime and what optimizations exist?

Expert

Answer

Razor parses .cshtml into C# classes, compiles them into temporary assemblies, and caches them. Runtime compilation is slower but flexible; precompiled views dramatically improve startup performance and CPU usage.

Quick Summary: In production, Razor views are precompiled by Roslyn at publish time — no .cshtml files needed. In development, Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation watches files and recompiles on change. The generated RazorPage class has an Execute() method that writes HTML chunks to a TextWriter using string pooling to minimize allocations.
Q136:

How does the View Engine pipeline work and how do multiple engines coexist?

Expert

Answer

View engines search for views, parse templates, generate executable output, and render HTML. Multiple engines coexist by being queried in order; the first match handles rendering.

Quick Summary: The view engine pipeline calls IViewEngine.FindView() on registered engines in order. RazorViewEngine searches by convention (/Views/{Controller}/{Action}.cshtml). You can register custom engines (Markdown, Handlebars) before or after Razor in MvcOptions.ViewEngines. The first engine that finds the view wins.
Q137:

What are Application Parts in ASP.NET Core and why are they important?

Expert

Answer

Application Parts let MVC discover controllers, views, pages, and Tag Helpers from assemblies or Razor Class Libraries. They enable modular architectures, plugin systems, and dynamic feature loading.

Quick Summary: Application Parts are registered with ApplicationPartManager and contribute controllers, views, tag helpers, and other MVC components to the app. By default, the entry assembly is an Application Part. Add external assemblies to load controllers from plugins: builder.Services.AddControllersFromApplication(typeof(PluginAssembly).Assembly).
Q138:

Why does ASP.NET Core enforce asynchronous patterns everywhere?

Expert

Answer

Async frees threads during I/O waits, prevents thread starvation, improves scalability, and avoids deadlocks. ASP.NET Core is designed for async performance from MVC to Razor to middleware.

Quick Summary: ASP.NET Core is built to handle thousands of concurrent requests per server. Synchronous I/O (blocking database calls, synchronous file reads) wastes threads waiting. Async I/O releases the thread to handle other requests. The thread pool scales to match load; blocking negates this. async Task everywhere is the correct default for all I/O-bound work.
Q139:

What is the role of Metadata Providers in MVC?

Expert

Answer

Metadata Providers supply display names, validation rules, formatting, and UI hints. They influence model binding, validation, scaffolding, and Tag Helpers, ensuring consistent UI rules across apps.

Quick Summary: Metadata Providers (IDisplayMetadataProvider, IValidationMetadataProvider) feed metadata about model properties to the view rendering pipeline — display names, data type hints, validation error messages. Tag helpers like asp-for use this metadata to generate correct HTML attributes. Implement a custom provider to centralize display/validation metadata outside DataAnnotations.
Q140:

What is the role of the Application Model in MVC and why do enterprises customize it?

Expert

Answer

The Application Model describes controllers, actions, parameters, routes, and filters. Enterprises customize it to enforce conventions, apply automatic routing, add versioning, or inject policies globally.

Quick Summary: The Application Model is an in-memory representation of all controllers, actions, and their attributes built at startup. IApplicationModelConvention implementations modify this model globally — add filters to all controllers, normalize route conventions, apply naming policies. This avoids repeating attributes across all controllers and enables reusable cross-cutting conventions.
Q141:

Why are View Components preferred over Partial Views in advanced architectures?

Expert

Answer

View Components include logic, support DI, run independently of controllers, and provide isolated UI modules. They are ideal for dynamic widgets, reusable dashboard blocks, and modular UI design.

Quick Summary: ViewComponents have InvokeAsync() with full DI support — they can query databases, consume services, run async logic. Partial Views just render a template with a passed model — no independent logic. ViewComponents are independently testable, reusable across different pages, and encapsulate their own data requirements. Use them for notification counts, sidebar widgets, shopping carts.
Q142:

How does ASP.NET Core protect against request body overconsumption?

Expert

Answer

ASP.NET Core enforces limits on request size, form size, field count, and upload sizes. It aborts oversized requests and streams bodies to prevent memory exhaustion.

Quick Summary: MaxRequestBodySize in Kestrel (default 30MB) and IIS limits prevent clients from sending oversized bodies. Per-action overrides: [RequestSizeLimit(bytes)] increases or [DisableRequestSizeLimit] removes the limit for specific actions. The body is also limited to not be buffered unless you explicitly enable request body buffering (EnableBuffering()).
Q143:

Why do large enterprises rely on Razor Class Libraries (RCLs)?

Expert

Answer

RCLs consolidate shared UI components, layouts, Tag Helpers, and styles across multiple applications. They support modular deployment, branding consistency, and reusable UI patterns.

Quick Summary: RCL packages Razor views, pages, components, and static files into a NuGet. The host app consumes the RCL and gets all its views automatically via the application part system. This enables shared UI — the same admin dashboard, the same login page — across 50 internal apps without copying code. Update the NuGet version to push UI changes everywhere.
Q144:

How does the Model Validation Pipeline work?

Expert

Answer

After model binding, validation attributes run, errors populate the ModelState dictionary, and filters may stop execution. This ensures invalid data never reaches application logic.

Quick Summary: After model binding: run DataAnnotation validators → run IValidatableObject.Validate() (cross-property rules) → run custom ValidationAttribute subclasses → populate ModelState. If FluentValidation is registered, its validators run instead of (or alongside) DataAnnotations. The pipeline is controlled via IObjectModelValidator. Check ModelState.IsValid before proceeding.
Q145:

What are Filters in MVC and how is their execution ordered?

Expert

Answer

Execution order: Authorization ? Resource ? Action ? Exception ? Result. Filters wrap different pipeline stages and are used for cross-cutting concerns like logging, auth, and caching.

Quick Summary: Filter execution order: Authorization filters (can short-circuit) → Resource filters (before/after model binding) → Action filters (before/after action execution) → Result filters (around result execution) → Exception filters (catch unhandled exceptions). Within each filter type, Global → Controller → Action scope order applies. IOrderedFilter controls ordering within same scope.
Q146:

What is the difference between Authentication and Authorization in ASP.NET Core?

Expert

Answer

Authentication verifies identity, while Authorization determines access rights. ASP.NET Core uses modular auth handlers and policy-based authorization for flexible security design.

Quick Summary: Authentication identifies who the user is — reads the cookie or JWT, validates it, and populates HttpContext.User with claims. Authorization decides what they can do — reads HttpContext.User's claims/roles against [Authorize] policies and requirements. Auth must always complete before authorization runs. A user can be authenticated but not authorized for a specific resource.
Q147:

How does Razor Layout Hierarchy work and how are nested layouts resolved?

Expert

Answer

Razor resolves the requested view, then the inner layout, then outer layouts, merging sections at each level. This supports multi-layered branding and UI composition.

Quick Summary: Each view declares Layout = "_Layout" (or inherits from _ViewStart.cshtml). Nested layouts: child layout sets its Layout to a parent layout. At render time, Razor renders the innermost view first, then wraps each layout around it. @RenderBody() injects the child's output. @RenderSection("Scripts", required: false) injects optional named sections from child views.
Q148:

How does ASP.NET Core support Localization and Globalization?

Expert

Answer

ASP.NET Core uses culture providers, resource-based translations, and formatting rules for dates and numbers. It detects culture via headers, route values, cookies, or query strings.

Quick Summary: UseRequestLocalization() middleware reads culture from URL segment, cookie, or Accept-Language header and sets CultureInfo.CurrentCulture. Resource files (.resx) store translated strings. IStringLocalizer injects into controllers/views to look up translations. Format: Resources/Controllers.HomeController.fr.resx for French translations of HomeController strings.

Curated Sets for .NET Core

No curated sets yet. Group questions into collections from the admin panel to feature them here.

Ready to level up? Start Practice