Skip to main content

.NET Core Interview Cheat Sheet

Top 50 interview questions with concise answers. Print this page or save as PDF for offline study.

View All .NET Core Questions

1. What is inheritance?

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.

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

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.

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

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.

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

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.

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

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.

6. Why does the order of middleware matter so much?

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.

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

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.

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

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.

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

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.

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

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.

11. What is Routing in ASP.NET Core?

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.

12. Compare Conventional Routing vs Attribute Routing.

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.

13. What is Model Binding?

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.

14. What is Model Validation and how does it work?

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.

15. What are Filters and why are they important?

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.

16. What are Razor Views?

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.

17. Explain Layouts, Partial Views, and View Components.

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.

18. What are Tag Helpers?

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.

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

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.

20. What is Anti-Forgery and why is it required?

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

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.

29. What is Razor View Compilation and why does it matter?

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.

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

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.

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

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.

32. What is ViewData, ViewBag, and TempData?

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.

33. Explain Endpoint Routing in detail.

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.

34. What is Model Binding Value Providers?

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.

35. Explain Custom Model Binding and when it is required.

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.

36. What is ModelState and why is it crucial?

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.

37. What are Filters and what are their use cases?

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.

38. What is an Exception Filter vs Middleware Exception Handling?

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

39. Explain ViewComponents and how they differ from Partial Views.

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.

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

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.

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

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.

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

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.

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

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.

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

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.

45. How does ASP.NET Core prevent request body overconsumption?

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.

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

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.

47. Explain how the Model Validation Pipeline works.

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.

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

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.

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

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.

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

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.
Ready to level up? Start Practice