Skip to main content

Command Palette

Search for a command to run...

Why Does a Controller Inherit from ControllerBase in an ASP.NET Web API Application?

Published
2 min read

Note: This is applicable when developing purely an application programming interface (API) without the intention of designing the views or rendering razor pages as done in ASP.NET MVC applications. If your application has both APIs and Razor views, use the full Controller class for controllers handling views and ControllerBase for API-only controllers


When writing an API and setting up a controller for our model, the controller needs to inherit from ControllerBase. This inheritance is essential because it provides the controller access to the full functionality of a web API without the additional overhead of handling views or Razor page rendering.

By inheriting from ControllerBase, the controller gains the following benefits:

  • Attributes and Filters: The controller can leverage various attributes and filters, such as [HttpGet], [HttpPost], and [Authorize]. These attributes streamline defining and securing endpoints.

  • Handling HTTP Requests and Responses: The controller is designed to process HTTP requests and return HTTP responses effectively. It supports various HTTP response methods, such as:

    • Ok(Object value)

    • NotFound(Object value)

    • BadRequest(Object value)

These methods allow the controller to deliver precise responses wrapped in an ActionResult.

[ApiController]
[Route("api/[controller]")]
public class MyApiController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new { Message = "Hello from API" });
    }
}

Overall, inheriting from ControllerBase ensures that the controller is lightweight, efficient, and optimized for web API development in ASP.NET applications.


Thank you for reading! I hope this explanation sheds light on why controllers inherit from ControllerBase ASP.NET. If you have any questions or need further clarification, feel free to reach out!

Attributions

And specifically, I would like to thank @osupersunny, my tutor, for the great work done for me.