📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Explain MVC in ASP.NET Core: controllers, actions and action results, and what the [ApiController] attribute changes. Then compare Razor Pages with MVC controllers plus Razor Views, and tell me when each fits.

ASP.NET Core MVC: controllers, actions, IActionResult and ActionResult<T>, the [ApiController] behaviours (attribute routing requirement, automatic 400 ValidationProblemDetails, binding source inference, ProblemDetails for error codes), and Razor Pages (page model, handler methods) versus MVC with Razor Views.

Intermediate Theory Intermediate apicontroller aspnet-core controllers mvc razor-pages razor-views

🎯 Key points

  • A controller is a class (ControllerBase for APIs, Controller adds view support) whose public methods are actions mapped to endpoints
  • Actions return IActionResult or ActionResult<T>; ActionResult<T> gives a typed body plus status-code results
  • [ApiController] requires attribute routing, returns automatic 400 ValidationProblemDetails when ModelState is invalid, infers [FromBody]/[FromRoute]/[FromQuery], and turns error status codes into ProblemDetails
  • Business-rule errors found inside the action are added with ModelState.AddModelError and returned via ValidationProblem() for the same 400 shape
  • Razor Views are .cshtml templates rendered by a controller action (return View(model)), suited to many related actions and shared layouts
  • Razor Pages are page-focused: a .cshtml file plus a PageModel with OnGet/OnPost handlers and file-system based routes, keeping each screen's concerns together
  • Both share Razor, tag helpers, model binding, validation, filters, anti-forgery protection and the same middleware pipeline; keep business logic in services, not controllers or PageModels

⏱ 30-second answer

In MVC, a controller is a class whose public methods are actions; each action becomes an endpoint and returns an action result (IActionResult, or ActionResult<T> for a typed body plus status codes). API controllers derive from ControllerBase; Controller adds view support. [ApiController] makes API behaviour explicit: attribute routing is required, an invalid ModelState returns an automatic 400 ValidationProblemDetails, binding sources are inferred (complex types from the body), and error status codes become ProblemDetails. For server-rendered UI there are two styles: MVC with Razor Views (a controller picks a .cshtml view) and Razor Pages (a .cshtml page with its own PageModel and OnGet/OnPost handlers). Razor Pages fits page-per-task, form-heavy apps; MVC fits when one controller serves many views or shares logic with APIs.

🗣 Full answer (senior)

How I would answer this in an interview

"MVC in ASP.NET Core is the controller-based model. A controller is a class, usually ending in Controller, and its public methods are actions. Routing maps each action to an endpoint, model binding fills its parameters, filters run around it, and it returns an action result: Ok, NotFound, CreatedAtAction, View, and so on. For APIs I use ActionResult<T> so I get a typed body for OpenAPI and can still return a status code like NotFound().

[ApiController] switches on the behaviours you want for an HTTP API. Attribute routing is mandatory, so no conventional routes. If model validation fails, the action never runs; the framework returns a 400 with ValidationProblemDetails listing the field errors. Binding sources are inferred: complex types from the body, route parameters from the route, the rest from the query, so you rarely write [FromBody]. And when you return a bare NotFound() or another error code, it's turned into a ProblemDetails body. You can apply it to a base class or the whole assembly.

For server-rendered HTML, Razor Views are templates a controller action renders with return View(model). Razor Pages are page-centric: Pages/Orders/Edit.cshtml plus an EditModel class with OnGet and OnPostAsync, routed by file path. I'd pick Razor Pages for a form-heavy admin or internal tool where each screen is a task, and MVC views when a controller naturally serves many related views or the app mixes HTML and API endpoints in the same controllers. The mistake I see is people thinking Razor Pages is 'Web Forms again'; it's MVC underneath with better cohesion per page."


[ApiController] behaviours

Behaviour Without it With it
Routing Conventional or attribute Attribute routing required
Invalid model Action runs; you check ModelState.IsValid Automatic 400 ValidationProblemDetails
Complex parameter source Form/query by default Inferred [FromBody]
return NotFound() body Empty ProblemDetails (ClientErrorMapping)
Multipart/form-data Manual Inferred for IFormFile

Razor Pages vs MVC views

Razor Pages MVC + Razor Views
Unit of organisation A page (view + PageModel) A controller with many actions and views
Routing Folder path (/Orders/Edit/{id?}) Attribute or conventional routes
Handlers OnGet, OnPostAsync, named handlers Actions
Best for Forms, CRUD screens, internal tools Larger apps with shared controller logic, mixed HTML + API
Shared features Razor syntax, tag helpers, layouts, binding, validation, anti-forgery, filters Same

Production example

An internal claims-processing tool built with Razor Pages kept each screen's GET, POST and validation in one 150-line PageModel, and new developers delivered their first screen in a day. The public API for the same system used [ApiController] controllers, where the automatic 400 removed about 200 lines of duplicated if (!ModelState.IsValid) checks.

🔍 What the interviewer is checking

Checks whether the candidate knows what MVC and [ApiController] do for them and can choose a UI model sensibly.

Green flags

  • Lists the concrete [ApiController] behaviours.
  • Uses ActionResult<T> and knows why.
  • Explains Razor Pages as page-focused MVC and chooses based on app shape.
  • Mentions anti-forgery and Post/Redirect/Get.

Red flags

  • Thinks [ApiController] is just a marker with no behaviour.
  • Checks ModelState manually everywhere in API controllers.
  • Equates Razor Pages with Web Forms.

📚 Learn in depth

1. How an action becomes an endpoint

At start-up, MVC's application model discovers controllers (public, non-abstract, Controller suffix or [Controller]), builds ActionDescriptors from methods and attributes, applies conventions, and creates one endpoint per action. When matched, the endpoint's delegate runs the action invoker:

Endpoint matched
  └► Authorisation filters
      └► Resource filters (before)
          └► Controller created (DI) ─► Model binding ─► Validation (ModelState)
              └► Action filters (before) ─► ACTION ─► Action filters (after)
          └► Exception filters (if thrown)
      └► Result filters ─► Result executes (JSON formatter, view engine)
  └► Resource filters (after)

2. IActionResult vs ActionResult<T>

ActionResult<T> has implicit conversions from T and from ActionResult, so return order; and return NotFound(); both compile. API Explorer reads T as the 200 response type. Returning T directly works but can't express other status codes without exceptions.

3. What [ApiController] really adds

It is an IApiBehaviorMetadata marker that triggers several application model conventions:

  • ModelStateInvalidFilter (order -2000): returns InvalidModelStateResponseFactory output, by default a 400 ValidationProblemDetails with a traceId.
  • InferParameterBindingInfoConvention: [FromBody] for complex types, [FromForm] for IFormFile, [FromRoute] for names in the route template, [FromQuery] otherwise.
  • ClientErrorResultFilter: converts IClientErrorActionResult (status >= 400) into ProblemDetails.
  • Each can be turned off via ApiBehaviorOptions (e.g. SuppressModelStateInvalidFilter).

4. Razor Views

return View(model) creates a ViewResult; the Razor view engine locates Views/{Controller}/{Action}.cshtml (then Views/Shared), the compiled view class renders HTML with the model, inside a layout (_Layout.cshtml). Views are compiled at build time since .NET 6.

5. Razor Pages

Each .cshtml under Pages/ with @page becomes an endpoint. Its PageModel gets [BindProperty] properties and handler methods selected by HTTP verb and optional ?handler= name. Anti-forgery validation is automatic for POSTs. Under the hood it reuses MVC's model binding, validation, filters and Razor compilation.

Try it yourself

  1. Create an API controller without [ApiController], post invalid JSON, and see the action run; add the attribute and compare.
  2. Customise InvalidModelStateResponseFactory to add a custom errorCode.
  3. Build the same edit form as a Razor Page and as an MVC action + view; compare file count and lines.
  4. Return ActionResult<OrderDto> and inspect the OpenAPI schema; switch to IActionResult and compare.

💻 Code

An API controller with [ApiController] and a Razor Page handling a form.

// Controllers/OrdersController.cs
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;

namespace Claims.Web.Controllers;

[ApiController]                     // automatic 400s, binding inference, ProblemDetails errors
[Route("api/orders")]
public sealed class OrdersController(IOrderService orders) : ControllerBase
{
    [HttpGet("{id:int}")]
    public async Task<ActionResult<OrderDto>> Get(int id, CancellationToken ct)
        => await orders.FindAsync(id, ct) is { } order ? order : NotFound(); // NotFound becomes ProblemDetails

    [HttpPost]
    public async Task<ActionResult<OrderDto>> Create(CreateOrder cmd, CancellationToken ct) // [FromBody] inferred
    {
        // No ModelState check needed: invalid input never reaches here
        var order = await orders.CreateAsync(cmd, ct);
        return CreatedAtAction(nameof(Get), new { id = order.Id }, order);
    }
}

public sealed record CreateOrder([Required] string Sku, [Range(1, 100)] int Quantity);
public sealed record OrderDto(int Id, string Sku, int Quantity);
public interface IOrderService
{
    Task<OrderDto?> FindAsync(int id, CancellationToken ct);
    Task<OrderDto> CreateAsync(CreateOrder cmd, CancellationToken ct);
}
// Pages/Orders/Create.cshtml.cs: the page's GET, POST and validation live together
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Claims.Web.Controllers;

namespace Claims.Web.Pages.Orders;

public sealed class CreateModel(IOrderService orders) : PageModel
{
    [BindProperty] public CreateOrder Input { get; set; } = new("", 1);

    public void OnGet() { }

    public async Task<IActionResult> OnPostAsync(CancellationToken ct)
    {
        if (!ModelState.IsValid) return Page();      // redisplay the form with errors (no [ApiController] here)
        var order = await orders.CreateAsync(Input, ct);
        return RedirectToPage("Details", new { id = order.Id }); // Post/Redirect/Get
    }
}
@* Pages/Orders/Create.cshtml *@
@page
@model Claims.Web.Pages.Orders.CreateModel
<form method="post">  @* anti-forgery token added automatically *@
  <input asp-for="Input.Sku" /> <span asp-validation-for="Input.Sku"></span>
  <input asp-for="Input.Quantity" /> <span asp-validation-for="Input.Quantity"></span>
  <button type="submit">Create</button>
</form>

⚠ Common mistakes

  • Mistake: Checking ModelState.IsValid at the top of every [ApiController] action. Why it is wrong: ModelStateInvalidFilter runs before the action and returns the 400 when binding or attribute validation fails, so that check is dead code. Instead: Remove it; for business rules discovered inside the action (duplicate email, discontinued product), call ModelState.AddModelError(...) and return ValidationProblem(ModelState); so clients get the same 400 shape.
  • Mistake: Deriving API controllers from Controller. Why it is wrong: It pulls in view support (View(), TempData) that APIs don't need. Instead: Derive from ControllerBase.
  • Mistake: Returning IActionResult everywhere. Why it is wrong: OpenAPI can't infer the success type. Instead: ActionResult<T> or [ProducesResponseType].
  • Mistake: Fat controllers or PageModels holding data access and business rules. Why it is wrong: Logic can't be reused from APIs, jobs or tests and screens become hard to change. Instead: Keep them as thin adapters over application services.
  • Mistake: Treating Razor Pages as Web Forms. Why it is wrong: There is no view state or page life cycle events; it's MVC with page-level cohesion. Instead: Use it for page-per-task UIs.
  • Mistake: Forgetting Post/Redirect/Get after a successful form POST. Why it is wrong: A browser refresh resubmits the form. Instead: Redirect after a successful POST.
  • Mistake: Disabling anti-forgery validation to make AJAX posts work. Why it is wrong: It opens cookie-authenticated pages to CSRF. Instead: Send the token in a header and configure AddAntiforgery.

🏛 Senior insight: trade-offs

A senior treats [ApiController] as a contract: consistent 400s and ProblemDetails across all APIs, customised once in ApiBehaviorOptions rather than per action. For UI, the choice between Razor Pages and MVC views is about cohesion: Razor Pages keeps everything a screen needs together; MVC views share logic across screens. Both are mature; Blazor is a third option when you need rich interactivity, but server-rendered Razor remains the cheapest to build and host.

Option When it fits Cost When not to
[ApiController] controllers JSON APIs on MVC Some magic to learn Native AOT (use Minimal APIs)
Razor Pages Form-heavy internal tools, CRUD Less suited to shared action logic Pure APIs
MVC + Razor Views Larger apps, mixed HTML and APIs More files per feature Simple page-per-task apps
Blazor Rich interactive UI in C# Circuit or WASM complexity Mostly static pages

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about controllers as the API model. Why: Checks whether the candidate can compare controllers with the Minimal API model.
    How to answer

    Both sit on the same foundation: endpoint routing, middleware, DI, authentication and OpenAPI. The difference is the programming model. Minimal APIs map handlers directly with MapGet/MapPost, organise with route groups, return TypedResults, use endpoint filters, support Native AOT, and in .NET 10 get built-in DataAnnotations validation with AddValidation(). Controllers group actions in classes and bring the full MVC feature set: [ApiController] behaviours (automatic 400s, binding inference), the five MVC filter types, custom model binders, input/output formatters with content negotiation and JSON Patch. For a new API service I default to Minimal APIs organised by feature; I choose controllers when the team relies on MVC filters, formatters or existing conventions. The trade-off is less ceremony and AOT versus a richer, more conventional framework.

  2. When: Candidate mentions ProblemDetails for error status codes. Why: Checks how errors become ProblemDetails consistently across the app.
    How to answer

    In ASP.NET Core, register AddProblemDetails(), one or more IExceptionHandler implementations (.NET 8+) with AddExceptionHandler<T>(), and app.UseExceptionHandler() early in the pipeline. Handlers log once and map known exceptions to the right status code and an RFC 9457 ProblemDetails body, and never leak stack traces in production. For the process as a whole, AppDomain.CurrentDomain.UnhandledException is a last-chance notification: you can log and flush, but the process still terminates. TaskScheduler.UnobservedTaskException fires when a faulted task that nobody awaited is garbage-collected; it does not crash the process by default. In a BackgroundService, an unhandled exception in ExecuteAsync stops the host by default (.NET 6+). async void exceptions go to the synchronisation context and usually crash the process, so avoid async void except for event handlers.

↩ Usually asked after

More in ASP.NET Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me