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.
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.
"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 useActionResult<T>so I get a typed body for OpenAPI and can still return a status code likeNotFound().
[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 withValidationProblemDetailslisting 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 bareNotFound()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.cshtmlplus anEditModelclass withOnGetandOnPostAsync, 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 | 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 |
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.
Checks whether the candidate knows what MVC and [ApiController] do for them and can choose a UI model sensibly.
Green flags
[ApiController] behaviours.ActionResult<T> and knows why.Red flags
[ApiController] is just a marker with no behaviour.ModelState manually everywhere in API controllers.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)
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.
[ApiController] really addsIt 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.ApiBehaviorOptions (e.g. SuppressModelStateInvalidFilter).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.
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.
[ApiController], post invalid JSON, and see the action run; add the attribute and compare.InvalidModelStateResponseFactory to add a custom errorCode.ActionResult<OrderDto> and inspect the OpenAPI schema; switch to IActionResult and compare.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>
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.Controller. Why it is wrong: It pulls in view support (View(), TempData) that APIs don't need. Instead: Derive from ControllerBase.IActionResult everywhere. Why it is wrong: OpenAPI can't infer the success type. Instead: ActionResult<T> or [ProducesResponseType].AddAntiforgery.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 |
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.
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.
Last updated 23 Nov 2026.