que-son-y-como-usar-controlers-aspnet

What are and how to use controllers in ASP.NET

  • 3 min

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, 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, which are responsible for handling each of the requests (GET, POST, etc.).

In summary, controllers:

  1. Receive requests: Capture incoming requests, such as GET, POST, PUT, DELETE, etc.
  2. Process business logic: Execute the necessary logic to handle the request (like querying a database or performing calculations).
  3. 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 ControllersMVC Controllers
InheritanceControllerBaseController
Typical ReturnsJSON, XMLHTML (views)
Required Decoration[ApiController]None necessary
Main InteractionREST API, HTTP clientsBrowsers

API Controllers

API controllers are designed to handle RESTful requests. They inherit from ControllerBase and are not coupled 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;
    }
}
Copied!

MVC Controllers

MVC controllers are for web applications that render HTML views. They inherit from Controller, which extends ControllerBase adding view-specific functionality.

public class HomeController : Controller
{
    public IActionResult Index()
    {
        ViewData["Message"] = "Welcome to the ASP.NET Core course";
        return View();
    }

    public IActionResult Error()
    {
        return View("Error");
    }
}
Copied!

API controllers are more common in modern applications that return data.

On the other hand, MVC Controllers are for MVC projects (logically) which are somewhat outdated nowadays.

Enabling Controllers in ASP.NET Core

To use controllers in an application, we must ensure 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();
Copied!

Controller Detection

ASP.NET automatically detects controllers. We don’t need to add them manually, we just need to create them.

For auto-detection to work, we must create controllers based on a set of rules:

  • As mentioned, classes must inherit from ControllerBase (or Controller).
  • The controller name must end with the suffix Controller (for example, ProductsController).
[ApiController]
public class ProductsController : ControllerBase
{
    // ... rest of the code
}
Copied!

For API controllers, it is also recommended to decorate them with [ApiController].

This enables automatic validations and enhanced behavior for REST APIs (i.e., it’s not mandatory, but do it 😉).