Skip to main content

Mid .NET Core Interview Questions

Curated Mid-level .NET Core interview questions for developers targeting mid positions. 46 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

46 questions
Q1:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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