skip to content

MVC & Razor Pages

The MVC programming model: API controllers with [ApiController], the MVC filter pipeline, Razor views and layouts, tag helpers and view components, and Razor Pages. Interviewers expect fluency in it.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

28

In ASP.NET Core, when should a controller derive from ControllerBase instead of Controller, and which of AddControllers, AddControllersWithViews or AddMvc does it need?

level: juniorimportance: must knowfreq 80%

answer

  1. views or pure HTTP API?
  2. Controller derives from ControllerBase
  3. View, PartialView, Json, ViewBag live on Controller
  4. AddMvc = AddControllersWithViews + AddRazorPages
  5. MapControllers maps attribute-routed actions

basics

~10 s

A JSON API controller derives from ControllerBase, which carries the HTTP result helpers, and needs only AddControllers. Derive from Controller when actions render Razor views, and register AddControllersWithViews; AddMvc also adds Razor Pages.

solid answer

~40 s

`ControllerBase` is the base for controllers without view support: it exposes `HttpContext`, `User`, `ModelState`, `Url` and the result helpers such as `Ok`, `NotFound`, `NoContent`, `BadRequest` and `Problem`. `Controller` derives from it and adds what server-rendered pages need: `View`, `PartialView`, `ViewComponent`, `Json`, `ViewData`, `ViewBag`, `TempData`, plus overridable `OnActionExecuting`/`OnActionExecuted`, because it implements `IActionFilter` and `IAsyncActionFilter`. For a JSON API you call `builder.Services.AddControllers()`, which brings the MVC core plus ApiExplorer, authorization, CORS, data annotations and formatter mappings. `AddControllersWithViews()` adds views, the Razor view engine and the cache tag helper, and `AddMvc()` is that plus `AddRazorPages()`. Then `app.MapControllers()` maps the attribute-routed actions; calling it without the services throws an `InvalidOperationException`.

code

csharp · 21 lines
csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();          // API only: no views, no pages
builder.Services.AddScoped<IClaimStore, ClaimStore>();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();                       // attribute-routed actions
app.Run();

[ApiController]
[Route("api/claims")]
public class ClaimsController(IClaimStore store) : ControllerBase
{
    [HttpGet("{id:int}")]
    public async Task<ActionResult<ClaimDto>> GetClaimAsync(int id, CancellationToken ct)
    {
        var claim = await store.FindAsync(id, ct);
        return claim is null ? NotFound() : claim;
    }
}

go deeper

for a junior

Know that ControllerBase is for APIs and Controller adds views, and that AddControllers plus MapControllers is the minimum wiring for an API.

for a middle

Explain what each Add* call registers, why AddMvc is overkill for an API, and how MVC discovers controllers and public action methods.

for a senior

Spot accidental endpoints from public helpers, view services registered in API-only hosts, and per-request controller state mistaken for shared state.

for a principal

Set a convention for mixed sites: base class per controller, registration per host, and API controllers kept free of view dependencies.

## Two base classes, one pipeline ASP.NET Core MVC has a single action pipeline for both HTTP APIs and server-rendered pages. What differs is the **base class** your controller inherits and the **services** you register. - **`ControllerBase`** (namespace `Microsoft.AspNetCore.Mvc`, assembly Mvc.Core) is described in its own source as "a base class for an MVC controller without view support". It gives you the request (`HttpContext`, `Request`, `Response`, `User`), the binding state (`ModelState`), URL generation (`Url`) and dozens of factory methods that return `IActionResult` implementations: `Ok()`, `NotFound()`, `NoContent()`, `BadRequest()`, `Conflict()`, `Problem()`, `File()`, `Redirect()` and so on. - **`Controller`** (Mvc.ViewFeatures) is declared as `public abstract class Controller : ControllerBase, IActionFilter, IAsyncActionFilter, IDisposable`. On top of everything in `ControllerBase` it adds `View()`, `PartialView()`, `ViewComponent()`, `Json()`, the `ViewData`/`ViewBag`/`TempData` dictionaries and the `OnActionExecuting`, `OnActionExecuted` and `OnActionExecutionAsync` hooks you can override. A controller for an insurance-claims JSON API therefore derives from `ControllerBase`: deriving from `Controller` would compile, but it drags in view machinery the API never uses and offers `View()` to a class that has no views. `Json()` is not a reason to pick `Controller` either; returning the object (or `Ok(obj)`) already runs the configured JSON formatter. ## Registering the services | Call | What it registers | Typical app | |---|---|---| | `AddControllers()` | MVC core, ApiExplorer, authorization, CORS, data annotations, formatter mappings | JSON API (the `webapi` template with `--use-controllers`) | | `AddControllersWithViews()` | everything in `AddControllers()` plus views, the Razor view engine and the cache tag helper | MVC web app (the `mvc` template) | | `AddRazorPages()` | Razor Pages with views and tag helpers | Razor Pages app | | `AddMvc()` | `AddControllersWithViews()` followed by `AddRazorPages()` | an app that really uses both | `AddMvc()` is not wrong, but for a JSON-only API it registers view and page services you never use; it is a leftover of the ASP.NET Core 2.x era, when it was the only entry point. All four return an `IMvcBuilder`, so options chain on the result: `AddControllers().AddJsonOptions(...)` or `.ConfigureApiBehaviorOptions(...)`. ## Mapping the endpoints Registration alone exposes nothing. Since endpoint routing, controllers become endpoints when you map them: 1. `app.MapControllers()` adds endpoints for controller actions **without specifying any routes**, which means it maps attribute-routed actions (`[Route]`, `[HttpGet("{id}")]`). 2. `app.MapControllerRoute(...)` or `app.MapDefaultControllerRoute()` adds a conventional route as well, which is what the `mvc` template uses. 3. Each `Map*` call first checks for MVC's marker service; if `AddControllers` (or one of its siblings) was never called it throws `InvalidOperationException` with "Unable to find the required services". The reverse mistake is quieter: `AddControllers()` without any `MapControllers()` starts fine and every controller URL returns 404, because no endpoint was ever added to the routing table. ## How MVC finds controllers and actions `ControllerFeatureProvider` treats a type as a controller when it is a **public, non-abstract, non-generic, top-level class** that either ends in `Controller` or carries `[Controller]` (inherited). `ControllerBase` itself carries `[Controller]`, so `public class ClaimsEndpoints : ControllerBase` is discovered even without the suffix; `[NonController]` opts a type out. Inside a controller, every **public instance method** that is not generic, not a property accessor and not inherited from `object` or `IDisposable.Dispose` becomes an action. A public helper such as `CalculateExcess` therefore becomes an endpoint: on a controller with `[Route("api/claims")]` it inherits that template and answers it for any HTTP method, which can clash with the real actions. Helpers are made private, moved to a service or marked `[NonAction]`. `MvcOptions.SuppressAsyncSuffixInActionNames` defaults to `true`, so `GetClaimAsync` has the action name `GetClaim`. ## The lifetime of a controller MVC creates a **new controller instance for every request** it dispatches to that controller and resolves the constructor's dependencies from the request's service scope. A controller is not registered in DI by default and is never shared between requests, so a field on it is per-request state; anything that must outlive the request belongs in an injected service with the right lifetime. ## Mistakes interviewers listen for - **Copying `AddMvc()` from an old tutorial** into an API host: it works, but it registers Razor view and page services, tag helpers and their application parts that the API never touches, and it hides which features the app really depends on. - **Expecting `MapControllers()` to add a default route**: only attribute-routed actions are mapped, so a controller written for `{controller}/{action}` silently returns 404 until a conventional route is mapped. - **Storing state in controller fields** to share between requests: the instance dies with the request. - **Calling `View()` from an API controller** that derives from `Controller`: the call compiles, and only fails at runtime when the view services are missing. ## Choosing in practice - Pure HTTP API: `ControllerBase` + `AddControllers()` + `MapControllers()`. - Server-rendered MVC site: `Controller` + `AddControllersWithViews()` + `MapControllerRoute(...)`. - A site with both MVC views and Razor Pages: `AddControllersWithViews()` plus `AddRazorPages()` (or `AddMvc()`), and map both. - An API controller living inside an MVC site still derives from `ControllerBase`; the base class is chosen per controller, the registration per application.

  • Your API controller derives from Controller and someone calls View() in it by accident. What happens at runtime when there are no views registered?
    With only `AddControllers()` registered, `ViewResult` finds no view executor in DI and throws an `InvalidOperationException` saying it is unable to find the required services and pointing at `AddControllersWithViews()`. Deriving from `ControllerBase` turns that into a compile-time error instead, since `View()` simply does not exist there.
  • Does a public helper method on a controller become an endpoint?
    Any public, non-static, non-generic instance method is an action as far as MVC is concerned. On an attribute-routed controller, a method without its own route attribute inherits the controller's `[Route]` template with no HTTP-method constraint, and on a conventionally routed controller the default route reaches any action by name. Make helpers private, move them to a service, or mark them `[NonAction]`.
  • Is a controller instance reused across requests?
    No. MVC activates a new instance per request and resolves its constructor dependencies from that request's scope, then disposes it if it is disposable. State kept in controller fields disappears with the request, which is exactly why controllers can safely take scoped services such as a DbContext.

  • An API controller needs Controller so it can return JSON with Json().
  • AddMvc() is the right registration for a JSON-only API in .NET 10.
  • MapControllers also maps the conventional {controller}/{action}/{id?} route.
  • One controller instance is created at startup and shared by all requests.
  • A class deriving from ControllerBase is ignored unless its name ends with Controller.
open as a page

In ASP.NET Core Razor Pages, how do the @page directive, the Pages folder and OnGet or OnPost methods route a request to code?

level: juniorimportance: must knowfreq 62%

basics

~20 s

A .cshtml file under Pages starting with @page is an endpoint whose URL is its path, with Index also answering the folder URL; a template after @page appends segments. The PageModel method named On plus the HTTP verb, such as OnPostAsync, handles it.

open as a page

In an ASP.NET Core MVC view, what does asp-for generate on input, label and validation tag helpers, and how are tag helpers switched on?

level: juniorimportance: must knowfreq 66%

basics

~20 s

asp-for binds an element to a model property: an input gets name, id, type, value and data-val attributes, a label gets for and the display name, a validation span shows that field's error. @addTagHelper in _ViewImports.cshtml enables them.

open as a page

In ASP.NET Core MVC, which files does return View() search for, and when is a view in Views/Shared used instead?

level: juniorimportance: must knowfreq 68%

basics

~20 s

View() takes the view name from the action's route value and searches /Views/{controller}/{name}.cshtml, then /Views/Shared/{name}.cshtml (plus /Pages/Shared when Razor Pages are registered). A Shared view serves any controller that has no view of that name.

open as a page

In ASP.NET Core, what does the [ApiController] attribute change about a controller's actions, and how do you switch each behaviour off?

level: middleimportance: must knowfreq 75%

basics

~20 s

[ApiController] makes attribute routing mandatory, returns an automatic 400 for invalid model state, infers parameter binding sources, adds a multipart/form-data constraint for form files and turns bare 4xx results into ProblemDetails; ApiBehaviorOptions switches each off.

open as a page

In ASP.NET Core MVC, which filter kinds exist and in what order do they run around a controller action?

level: middleimportance: must knowfreq 72%

basics

~20 s

MVC runs authorization filters, then resource filters, then model binding, then action filters around the action, and result filters around the result's execution. Exception filters catch failures from controller creation to the action, not from result execution.

open as a page

In ASP.NET Core Razor Pages, what does [BindProperty] do on a PageModel property, and why does a GET request need SupportsGet = true?

level: middleimportance: must knowfreq 52%

basics

~20 s

[BindProperty] makes model binding fill a PageModel property before the handler runs, so the handler and the page both use it. Only non-GET requests are bound by default; SupportsGet = true also binds GET, such as a search term.

open as a page

In ASP.NET Core MVC, when would you build a view component instead of a partial view, and how do you write and invoke one?

level: middleimportance: must knowfreq 55%

basics

~20 s

Use a view component when a reusable widget needs its own logic or data, such as a basket summary on every page; a partial view only renders the model its caller passes. A view component is a class with InvokeAsync and its own view.

open as a page

In an ASP.NET Core MVC site, how do _ViewStart, _Layout, RenderBody and RenderSection give every listing page one layout with page-specific scripts?

level: middleimportance: must knowfreq 60%

basics

~10 s

_ViewStart.cshtml sets Layout = "_Layout" for every full view; the layout calls RenderBody() where the view's content goes and RenderSectionAsync("Scripts", required: false) where a view's @section Scripts block goes.

open as a page

In ASP.NET Core MVC, how do you write an action filter that records who called each payroll admin action and how long it took?

level: juniorimportance: should knowfreq 58%

basics

~20 s

Implement IAsyncActionFilter: record the user and start a Stopwatch, await next() to run the action, then read ActionExecutedContext for the result or exception and write the audit entry. Register it globally with Filters.Add<T>() or per controller with [ServiceFilter].

open as a page

In ASP.NET Core MVC views, when do you pass data with @model versus ViewData or ViewBag, and how do they relate?

level: juniorimportance: should knowfreq 62%

basics

~20 s

Pass the page's main data as a typed model with View(model) and @model, which the compiler checks. Use ViewData or ViewBag only for small extras such as the page title; ViewBag is a dynamic wrapper over the same ViewData dictionary.

open as a page

In an ASP.NET Core controller, why return ActionResult<T> instead of IActionResult or a plain T, and where does ActionResult<T> stop working?

level: middleimportance: should knowfreq 62%

basics

~20 s

ActionResult<T> lets one action return either the T value (200) or any ActionResult such as NotFound(), while ApiExplorer and OpenAPI still read T as the success type. Interface-typed expressions do not convert implicitly, so materialise them first.

open as a page

In ASP.NET Core 10, when do controllers still beat Minimal APIs for an HTTP API, and when is a Minimal API the better choice?

level: middleimportance: should knowfreq 66%

basics

~20 s

Controllers win when you need MVC's extensibility: custom model binders and validators, the filter pipeline, application-model conventions, output-formatter content negotiation, or an existing controller codebase. Minimal APIs win for new services, Native AOT and lower overhead.

open as a page

In an ASP.NET Core MVC payroll back office, how would an exception filter translate domain exceptions into HTTP responses, and what can it not catch?

level: middleimportance: should knowfreq 50%

basics

~10 s

Implement IExceptionFilter, check context.Exception for a domain type such as PayrollPeriodClosedException, set context.Result to a 409 ProblemDetails and ExceptionHandled = true. It cannot catch exceptions from resource filters, result filters or result execution.

open as a page

In ASP.NET Core Razor Pages, how do named handlers such as OnPostCancelAsync work, and how does asp-page-handler pick the one a form posts to?

level: middleimportance: should knowfreq 40%

basics

~20 s

A handler name is the text between the verb and Async: OnPostCancelAsync handles POSTs named Cancel. asp-page-handler="Cancel" on a form or button writes ?handler=Cancel into the URL, and the selector reads that query key or a handler route value.

open as a page

In an ASP.NET Core Razor Pages POST handler, when do you return Page() and when RedirectToPage(), and what does each one do?

level: middleimportance: should knowfreq 48%

basics

~20 s

Page() renders the current page in the same request, keeping posted values and ModelState errors, which suits a failed validation; OnGet does not run. RedirectToPage() sends a 302 to a page's URL so the browser issues a GET, which suits success.

open as a page

For a server-rendered ASP.NET Core app, when would you choose Razor Pages over MVC controllers with views, and what do the two share?

level: middleimportance: should knowfreq 44%

basics

~20 s

Choose Razor Pages when the UI is a set of screens, each owning its GET and POST logic; choose MVC controllers when many actions share a controller or mix views and JSON. Both share MVC's binding, validation, tag helpers and layouts.

open as a page

In ASP.NET Core MVC, how do the anchor and form tag helpers turn asp-controller, asp-action and asp-route-* attributes into a URL?

level: middleimportance: should knowfreq 46%

basics

~20 s

Both helpers pass asp-controller, asp-action, asp-area and each asp-route-{name} value to MVC's URL generation; a value matching a route parameter fills that segment, any other becomes a query-string pair, and an omitted controller or action reuses the current one.

open as a page

In an ASP.NET Core 10 MVC layout, what do the environment tag helper and asp-append-version do, and how does MapStaticAssets change asp-append-version?

level: middleimportance: should knowfreq 38%

basics

~20 s

The environment tag helper renders its content only when IWebHostEnvironment.EnvironmentName matches include and not exclude. asp-append-version busts caches: with MapStaticAssets it writes the fingerprinted asset URL, otherwise it appends ?v= and a hash of the file.

open as a page

In ASP.NET Core MVC, when should a listings page use a partial view, how is the partial found, and what data does it receive?

level: middleimportance: should knowfreq 48%

basics

~20 s

Use a partial for markup repeated across views, such as a listing card. It is found like a view (controller folder, then Shared) and receives the model you pass plus a copy of the parent's ViewData, without _ViewStart or a layout.

open as a page

In ASP.NET Core 10, why does AddRazorRuntimeCompilation produce the ASPDEPR003 warning, and how should .cshtml edits reach a running app instead?

level: middleimportance: should knowfreq 38%

basics

~20 s

In .NET 10 Razor runtime compilation is obsolete (ASPDEPR003): views are already compiled at build and publish, runtime compilation disables Hot Reload and isn't meant for production. Use Hot Reload (dotnet watch) in development and rebuild and redeploy for production.

open as a page

An ASP.NET Core insurance-claims search action keeps querying the database after callers disconnect; how do you make the controller honour cancellation, and what happens when it fires?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Add a CancellationToken parameter to the action, which MVC binds to HttpContext.RequestAborted, and pass it to every async call. A disconnect then throws OperationCanceledException, which the exception middleware logs at Debug and maps to 499.

open as a page

In ASP.NET Core MVC, when do you use ServiceFilter, TypeFilter or a custom IFilterFactory to give a filter constructor dependencies, and what can IsReusable break?

level: seniorimportance: should knowfreq 42%

basics

~10 s

[ServiceFilter] resolves a DI-registered filter, [TypeFilter] builds an unregistered one with ActivatorUtilities and extra Arguments, and a custom IFilterFactory gives an attribute both parameters and services. IsReusable = true caches instances, capturing scoped dependencies.

open as a page

In ASP.NET Core Razor Pages, how do you run code around every page handler with IPageFilter, PageModel overrides or AddRazorPages conventions, and why don't action filters apply?

level: seniorimportance: should knowfreq 27%

basics

~10 s

Implement IPageFilter or IAsyncPageFilter, whose hooks run after handler selection, before the handler and after it, and register it globally, per folder through RazorPagesOptions.Conventions, or on the PageModel. Action filters never run for pages.

open as a page

In ASP.NET Core, how do you write a custom tag helper, and how do HtmlTargetElement, Process and TagHelperOutput decide what it renders?

level: seniorimportance: should knowfreq 34%

basics

~10 s

Derive from TagHelper, choose the element with [HtmlTargetElement] or the class-name convention, expose attributes as properties, and override Process or ProcessAsync to change TagHelperOutput: TagName, Attributes and Content. Then register the assembly with @addTagHelper.

open as a page

In ASP.NET Core MVC, how do filter scope and the Order property decide which filter runs first, and when does a result filter not run at all?

level: seniorimportance: nice to knowfreq 35%

basics

~20 s

MVC sorts filters by Order (default 0) and uses scope only to break ties: global, then controller, then action. Lower Order wraps higher. Ordinary result filters skip authorization or resource short-circuits and handled exceptions; IAlwaysRunResultFilter does not.

open as a page

In an ASP.NET Core MVC view, how does the cache tag helper store a rendered fragment, how long by default, and what varies its entries?

level: seniorimportance: nice to knowfreq 21%

basics

~20 s

The cache tag helper renders its content once and keeps the HTML in a private in-memory cache on each server, for a 30-second sliding expiry unless told otherwise. vary-by-* attributes split entries by user, route, query, header, cookie or culture.

open as a page

In ASP.NET Core MVC, how would an IViewLocationExpander make a white-label listings site look for agency-specific views first, and why does PopulateValues matter?

level: seniorimportance: nice to knowfreq 22%

basics

~10 s

Implement IViewLocationExpander: PopulateValues stores the agency in context.Values, and ExpandViewLocations returns agency paths before the defaults. Register it in RazorViewEngineOptions.ViewLocationExpanders. Skipping the Values entry makes the lookup cache serve one agency's views to all.

open as a page