A controller is a widely used concept in ASP.NET. A controller is a class that manages incoming HTTP requests and returns a response.
That is to say, basically a controller is the piece of code responsible for receiving requests and returning responses associated with an endpoint.
To do this, controllers are composed of methods, which we call actions, that are responsible for handling each of the requests (GET, POST, etc).
In summary, controllers:
- Receive requests: Capture incoming requests, such as
GET
,POST
,PUT
,DELETE
, etc. - Process business logic: Execute the necessary logic to handle the request (such as querying a database or performing calculations).
- Return a response: Generate and return an HTTP response (an HTML view, data in JSON format)
Types of controllers in ASP.NET Core
In ASP.NET a controller is a class that inherits from the base class ControllerBase
(for APIs) or Controller
(for MVC applications).
There are two main types of controllers:
Feature | ✅ API Controllers | MVC Controllers |
---|---|---|
Inheritance | ControllerBase | Controller |
Typical returns | JSON, XML | HTML (views) |
Required decoration | [ApiController] | None needed |
Main interaction | REST API, HTTP clients | Browsers |
API Controllers
API controllers are designed to handle RESTful requests. They inherit from ControllerBase
and are not tied to views.
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<string>> GetProducts()
{
return Ok(new[] { "Product1", "Product2" });
}
[HttpPost]
public IActionResult CreateProduct([FromBody] Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id)
{
var product = new Product { Id = id, Name = "Product1" };
return product;
}
}
MVC Controllers
MVC controllers are for web applications that render HTML views. They inherit from Controller
, which extends ControllerBase
by adding view-specific functionalities.
public class HomeController : Controller
{
public IActionResult Index()
{
ViewData["Message"] = "Welcome to the ASP.NET Core course";
return View();
}
public IActionResult Error()
{
return View("Error");
}
}
API controllers are more common in modern applications that return data.
In contrast, MVC controllers are for MVC projects (logic) that are somewhat outdated today.
Enabling controllers in ASP.NET Core
To use controllers in an application, we must ensure that they are enabled in the ASP.NET pipeline during application configuration.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Add services for controllers
builder.Services.AddControllers();
app.UseRouting();
// Add the controller mapping middleware
app.MapControllers();
app.Run();
Controller detection
ASP.NET automatically detects controllers. We do not need to add them manually; we just need to create them.
For autodetection to work, we must create controllers based on a series of rules:
- As mentioned, classes must inherit from
ControllerBase
(orController
). - The name of the controller must end with the suffix
Controller
(for example,ProductsController
).
[ApiController]
public class ProductsController : ControllerBase
{
// ... rest of the code
}
For API controllers, it is also recommended to decorate them with [ApiController]
.
This enables automatic validations and improved behavior for REST APIs (that is, it is not mandatory, but advisable 😉).