Controller vs ControllerBase
Both are base classes used to create controllers in ASP.NET Core.
| Feature | Controller |
ControllerBase |
|---|---|---|
| Primary use | MVC web applications | Web APIs |
| Razor View support | Yes | No |
View() method |
Available | Not available |
ViewBag |
Available | Not available |
ViewData |
Available | Not available |
TempData |
Available | Not available |
| JSON responses | Yes | Yes |
| HTTP results | Yes | Yes |
| Base class | Inherits from ControllerBase |
Base API controller class |
| Common attribute | Usually no [ApiController] |
Usually [ApiController] |
Controller Example
Used when returning Razor Views:
public class ProductController : Controller
{
public IActionResult Index()
{
return View();
}
}
ControllerBase Example
Used when returning API data:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
return Ok(new[] { "Laptop", "Mobile" });
}
}
Key Points
- Use
Controllerfor MVC applications that return HTML/Razor Views. - Use
ControllerBasefor Web APIs that return JSON or HTTP responses. Controllerinherits fromControllerBaseand adds View-related features.- Both provide methods such as
Ok(),NotFound(),BadRequest()andRedirect(). - Avoid using
Controllerfor APIs unless View functionality is genuinely required.