9.2 — Controllers: Controller vs ControllerBase¶
← Roadmap · Section: 9. MVC, Razor Pages and Views Prev: 9.1 The MVC pattern · Next: 9.3 Action results
Markers: 🔥 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
ControllerBasehas everything an API needs —Ok(),NotFound(),User,ModelState. No view support.Controllerinherits from it and adds view-related members —View(),ViewData,TempData,PartialView().- For a Web API, inherit
ControllerBase. UsingControllerpulls in view machinery you will never call.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
ControllerBase |
an abstract class | The API-focused base. Result helpers, User, ModelState, Url, HttpContext. |
Controller |
an abstract class | Inherits ControllerBase and adds views — View(), ViewData, TempData. |
| Action | a public method on a controller | Handles one request. Discovered by convention. |
[NonAction] |
an attribute | Marks a public method as not an action. |
| Controller discovery | a convention | Any public class ending in Controller, or marked [Controller], in the assembly. |
[ApiController] |
an attribute | Enables API conventions. See 10.4. |
ModelState |
a property | Validation results from model binding. See 11.5. |
User |
a property (ClaimsPrincipal) |
The authenticated caller. Shortcut for HttpContext.User. |
Url |
a property (IUrlHelper) |
Link generation. See 8.6. |
[ActionName] |
an attribute | Overrides the name used in routing and link generation. |
The concept¶
Two base classes, one difference¶
Controller inherits from ControllerBase. That is the whole relationship:
ControllerBase gives you:
- Result helpers —
Ok(),NotFound(),BadRequest(),CreatedAtAction() HttpContext,Request,ResponseUser— the authenticated principalModelState— validation resultsUrl— link generation
Controller adds:
View()andPartialView()ViewData,ViewBag,TempData(9.6)OnActionExecuting/OnActionExecutedoverrides
A picture: a van and a van with a passenger seat. Everything that makes it a vehicle is in the base. The passenger seat is only useful if you carry passengers — and if you never do, it is weight you are hauling around.
Which to use¶
Web API → ControllerBase. You will never call View(), so inheriting the view members means
a larger surface with methods that would throw if used
(9.1 — AddControllers does not register a view engine).
Server-rendered pages → Controller. You need View().
⚠️ The template default is Controller, which is right for an MVC project and wrong for an
API. If you create a Web API project the template correctly uses ControllerBase — but people
copying a controller from an MVC project into an API often bring the wrong base class with them.
How it works¶
The simple version¶
// ── API ──
[ApiController]
[Route("api/[controller]")]
public class OrdersController(IOrderService orders) : ControllerBase
{
[HttpGet("{id:guid}")]
public async Task<ActionResult<OrderDto>> Get(Guid id, CancellationToken ct)
{
var order = await orders.GetAsync(id, ct);
return order is null ? NotFound() : Ok(order); // ✓ from ControllerBase
}
}
// ── Server-rendered pages ──
[Route("orders")]
public class OrdersController(IOrderService orders) : Controller
{
[HttpGet("{id:guid}")]
public async Task<IActionResult> Details(Guid id, CancellationToken ct)
{
var order = await orders.GetAsync(id, ct);
if (order is null) return NotFound();
return View(OrderDetailsViewModel.From(order)); // ✓ needs Controller
}
}
How controllers are discovered¶
The framework scans the assembly for classes that are:
- Public and non-abstract, and
- Named
*Controller, or marked[Controller], or inherit fromControllerBase
public class OrdersController : ControllerBase { } // ✓ found
[Controller] public class Orders : ControllerBase { } // ✓ found — attribute
[NonController] public class HelperController { } // ✗ excluded
⚠️ Inheriting ControllerBase is enough on its own, so a class named OrdersApi that inherits
it is still discovered. That surprises people who assume the naming convention is required.
⚠️ Every public method is an action¶
public class OrdersController : ControllerBase
{
[HttpGet]
public IActionResult List() { }
// ⚠️ PUBLIC — the framework treats this as an action too
public string FormatReference(Order order) => $"ORD-{order.Number:D6}";
}
That helper becomes a routable action. With conventional routing it gets a URL; with
[ApiController] it throws at startup because it has no route attribute
(8.3).
Two fixes:
private string FormatReference(Order order) => ...; // ✓ make it private
[NonAction]
public string FormatReference(Order order) => ...; // ✓ or exclude it explicitly
Better still: a helper on the controller usually belongs elsewhere — on the ViewModel, or in a service (9.1).
How it actually works — useful members¶
public class OrdersController : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Create(CreateOrderRequest request, CancellationToken ct)
{
// Who is calling
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
// Validation state — automatic with [ApiController], see 10.4
if (!ModelState.IsValid) return ValidationProblem(ModelState);
// Link generation — see 8.6
var url = Url.Action(nameof(Get), new { id = order.Id });
// The raw context, when you genuinely need it
var ip = HttpContext.Connection.RemoteIpAddress;
return CreatedAtAction(nameof(Get), new { id = order.Id }, order);
}
}
⚠️ User is never null but may be unauthenticated. Check
User.Identity?.IsAuthenticated rather than a null check
(5.8).
Constructor injection¶
Controllers are created per request and their dependencies resolved from the request scope (6.5):
public class OrdersController(
IOrderService orders,
ILogger<OrdersController> logger) : ControllerBase { }
Primary constructors (C# 12) removed most of the boilerplate here (1.26).
⚠️ Every dependency is resolved for every request, regardless of which action runs. If one
action needs something expensive, [FromServices] on that action's parameter defers it
(6.9).
The deeper detail — controllers are not singletons¶
⚠️ A new controller instance is created for each request, so instance fields are per request, not shared:
public class OrdersController : ControllerBase
{
private int _count; // safe — a new instance per request
private static int _total; // ⚠️ SHARED across all concurrent requests
}
The static field is the problem — it needs thread safety (2.18) and it is a memory leak risk if it accumulates (3.5).
And because a controller is per request, it is disposable if you implement IDisposable — the
framework disposes it when the request ends. You rarely need that; injected services are disposed
by the scope (6.10).
Async actions¶
// ✓ async all the way, with a cancellation token
[HttpGet("{id:guid}")]
public async Task<ActionResult<OrderDto>> Get(Guid id, CancellationToken ct)
=> await orders.GetAsync(id, ct) is { } o ? Ok(o) : NotFound();
⚠️ Always take a CancellationToken. Model binding supplies HttpContext.RequestAborted
automatically, so it costs one parameter and means the server stops working on a response nobody
will receive (2.14).
⚠️ Never block on async work — .Result or .Wait() in an action pins a thread-pool thread
and causes thread-pool starvation under load
(2.13).
Code¶
A realistic API controller:
[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class OrdersController(
IOrderService orders,
ILogger<OrdersController> logger) : ControllerBase // ← Base, not Controller
{
[HttpGet(Name = "Orders_List")]
[ProducesResponseType<PagedResult<OrderDto>>(StatusCodes.Status200OK)]
public async Task<IActionResult> List(
[FromQuery] int pageNumber = 1,
[FromQuery] int pageSize = 20,
CancellationToken ct = default)
=> Ok(await orders.ListAsync(pageNumber, pageSize, ct));
[HttpGet("{id:guid}", Name = "Orders_Get")]
[ProducesResponseType<OrderDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<OrderDto>> Get(Guid id, CancellationToken ct)
=> await orders.GetAsync(id, ct) is { } order ? Ok(order) : NotFound();
[HttpPost]
[ProducesResponseType<OrderDto>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create(CreateOrderRequest request, CancellationToken ct)
{
// No ModelState check needed — [ApiController] returns 400 automatically. See 10.4.
var order = await orders.CreateAsync(request, ct);
logger.LogInformation("Order {OrderId} created by {UserId}",
order.Id, User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
return CreatedAtRoute("Orders_Get", new { id = order.Id }, order);
}
// Not an action — excluded explicitly. Better still, move it to the DTO.
[NonAction]
public static string FormatReference(int number) => $"ORD-{number:D6}";
}
And the MVC equivalent, where Controller is the right base:
[Route("orders")]
public class OrdersController(IOrderService orders) : Controller // ← Controller
{
[HttpGet("{id:guid}")]
public async Task<IActionResult> Details(Guid id, CancellationToken ct)
{
var order = await orders.GetAsync(id, ct);
if (order is null) return NotFound();
return View(OrderDetailsViewModel.From(order)); // needs Controller
}
[HttpPost("{id:guid}/cancel")]
[ValidateAntiForgeryToken] // see 17.4
public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
{
var result = await orders.CancelAsync(id, ct);
if (!result.IsSuccess)
TempData["Error"] = result.Reason; // survives the redirect
return RedirectToAction(nameof(Details), new { id });
}
}
⚠️ [ValidateAntiForgeryToken] on the form POST is not optional for a cookie-authenticated
site — without it the action is open to cross-site request forgery
(17.4). API controllers using bearer tokens do not need
it, because the browser does not attach the token automatically.
Interview questions¶
Q: What is the difference between Controller and ControllerBase?
ControllerBase is the API-focused base — it has the result helpers like Ok and NotFound,
plus User, ModelState, Url and HttpContext. Controller inherits from it and adds
view-related members: View(), PartialView(), ViewData, ViewBag and TempData. For a Web
API you inherit ControllerBase, because you will never render a view and inheriting the view
members gives you a larger surface with methods that would fail anyway — AddControllers does not
register a view engine at all.
Q: How does ASP.NET Core find your controllers?
It scans the assembly for public non-abstract classes that either end in Controller, carry the
[Controller] attribute, or inherit from ControllerBase. Inheriting the base class is enough on
its own, so a class named OrdersApi deriving from ControllerBase is still discovered — the
naming convention is not strictly required. You can exclude one with [NonController].
Q: What happens if you add a public helper method to a controller?
It becomes an action. The framework treats every public method as routable, so a formatting helper
gets a URL under conventional routing, or throws at startup under [ApiController] because it has
no route attribute. You fix it by making the method private or marking it [NonAction] — though
usually the better answer is that a helper on a controller belongs somewhere else, on the
ViewModel or in a service.
Q: What is the lifetime of a controller?
Per request. A new instance is created for each request and its constructor dependencies are
resolved from that request's DI scope, so instance fields are safely per request. Static fields
are not — those are shared across every concurrent request and need thread safety. It also means
every constructor dependency is resolved for every request regardless of which action runs, so if
one action needs something expensive, [FromServices] on that action's parameter defers it to
where it is used.
Traps ⚠️¶
- Using
Controllerfor an API brings view members that would throw, since no view engine is registered. - Every public method is an action. Make helpers private or
[NonAction]. - Inheriting
ControllerBaseis enough for discovery, regardless of the class name. Useris never null but may be unauthenticated. CheckIdentity?.IsAuthenticated.- Static fields on a controller are shared across concurrent requests.
- All constructor dependencies resolve per request, even for actions that never use them.
- Missing
CancellationTokenmeans the server keeps working after the client disconnects. - Blocking on async work in an action causes thread-pool starvation under load.
- Forgetting
[ValidateAntiForgeryToken]on a cookie-authenticated form POST is a CSRF hole.
Related¶
- 9.1 The MVC pattern — keeping controllers thin
- 9.3 Action results — what these methods return
- 9.6 TempData — the
Controller-only members - 10.4 ApiController — automatic 400s and inferred binding
- 8.3 Attribute routing — the route attributes
- 11.5 ModelState — validation results
- 6.9 Injection styles —
[FromServices] - 17.4 CSRF — antiforgery on form posts