skip to content

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.