Top .NET Core Interview Questions

Curated .NET Core interview questions and answers across difficulty levels.

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 { }


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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.
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.

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.

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.

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.

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.

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.
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.

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.
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.

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.

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.

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.

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.

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.

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.
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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.
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.

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.

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.
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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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
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.

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.

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.

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.

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.

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.

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.

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.

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
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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

Curated Sets for .NET Core

Top .NET Core Interview Questions and Answers (Beginner to Expert)

Top .NET Core Interview Questions and Answers (Beginner to Expert)

Complete .NET Core interview questions and answers covering beginner, junior, mid-level, senior, and expert concepts for freshers and experienced developers.

Includes beginner, junior, mid-level, senior, and expert-level .NET Core interview questions with real-world examples.
Ready to level up? Start Practice