Scaling Up: Moving to Controllers
6 min read
Welcome back, developer. ☕
In our previous sessions, we utilized Minimal APIs. They were sleek, fast, and required very little boilerplate. You wrote your logic directly inside Program.cs, and life was simple.
However, imagine a scenario: your application grows. You are no longer managing just a "Todo List." You are building an enterprise-grade e-commerce system with Users, Orders, Inventory, Payments, and Shipping logic. Suddenly, your Program.cs file is 5,000 lines long. You have to scroll for three minutes just to find the DELETE endpoint for a User.
Fun Fact: Searching through a 5,000-line single file is the number one cause of developers switching to farming as a career choice. 🚜
To prevent this architectural chaos, ASP.NET Core provides a robust structure known as Controllers. Today, we move from the functional style of Minimal APIs to the object-oriented structure of Controller-based APIs.
1. Controllers vs. Minimal APIs: When and Why to Switch
The Definition
Minimal APIs define routes and logic typically inside the Program.cs file using lambda expressions.
Controllers are C# classes that group related HTTP request handling logic together.
The Problem
When building complex applications, placing all routing and business logic in one file violates the Separation of Concerns principle. It makes the code difficult to test, difficult to read, and difficult to maintain by a team of developers.
The Solution
Controllers solve this by organizing code by domain (e.g., all "User" logic goes into a UsersController).
When to Switch?
While Minimal APIs are excellent for microservices and simple apps, Controllers are often preferred when:
- Complexity: You need complex model binding, validation, or content negotiation.
- Organization: You prefer the Object-Oriented pattern where dependencies are injected via the class constructor.
- Conventions: You want to leverage built-in conventions (like automatic 400 responses) provided by the
[ApiController]attribute.
Think of Minimal APIs as a speed boat 🚤 (fast, agile, limited capacity) and Controllers as a container ship 🚢 (structured, carries a massive load, slightly heavier setup).
2. Creating Your First API Controller: The ControllerBase Class
Let us get strictly technical. To use controllers, we must first configure the dependency injection container and the middleware pipeline in Program.cs.
Step 1: Configuration in Program.cs
Unlike Minimal APIs, Controllers require explicit registration.
var builder = WebApplication.CreateBuilder(args);
// 1. Add services to the container.
// This registers the necessary services to handle controllers.
builder.Services.AddControllers();
var app = builder.Build();
// 2. Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
// 3. Map the controller routes.
// This tells the app to look for Controller classes and register their routes.
app.MapControllers();
app.Run();Step 2: The Controller Structure
By convention, controllers are placed in a folder named Controllers.
A Web API controller class should inherit from ControllerBase.
⚠️ Crucial Industry Standard:
Do not inherit from theControllerclass if you are building a Web API. TheControllerclass adds support for Views (MVC - Razor Pages), which adds unnecessary overhead. Always useControllerBasefor pure APIs.
Example: The Gadget Controller
Create a file Controllers/GadgetsController.cs:
using Microsoft.AspNetCore.Mvc;
namespace MyApi.Controllers
{
// The [ApiController] attribute enables opinionated API behaviors,
// such as automatic HTTP 400 responses on validation errors.
[ApiController]
// We will discuss [Route] in the next section.
[Route("[controller]")]
public class GadgetsController : ControllerBase
{
// A simple in-memory list for demonstration
private static readonly List<string> Gadgets = new()
{
"Quantum Tuner",
"Sonic Screwdriver",
"Portal Gun"
};
[HttpGet]
public IEnumerable<string> Get()
{
return Gadgets;
}
}
}This class is now a dedicated space for all logic regarding "Gadgets."
3. Attribute Routing: Defining Paths Directly on Methods
The Problem
In Minimal APIs, you defined routes like app.MapGet("/gadgets", .... inside the main file. In Controllers, the class doesn't inherently know what URL it answers to.
The Solution
Attribute Routing. We use C# attributes (metadata tags above classes and methods) to define how URLs map to specific methods.
Controller-Level Routing
Look at the class definition from the previous example:
[Route("api/[controller]")]
public class GadgetsController : ControllerBaseThe [controller] token is a placeholder. ASP.NET Core automatically replaces it with the class name minus the word "Controller".
- Class:
GadgetsController-> Route:api/gadgets - Class:
UsersController-> Route:api/users
Method-Level Routing
Inside the class, we decorate methods with HTTP Verb attributes.
// GET: api/gadgets
[HttpGet]
public IActionResult GetAll()
{
// Returns 200 OK
return Ok(Gadgets);
}
// GET: api/gadgets/5
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
// Logic to find gadget by ID would go here
return Ok($"You requested gadget number {id}");
}
// POST: api/gadgets
[HttpPost]
public IActionResult Create()
{
return CreatedAtAction(nameof(GetById), new { id = 99 }, "New Gadget");
}Academic Note: This creates a predictable, RESTful URL structure. The routing logic is co-located with the code it executes, making debugging significantly easier than hunting through a central routing file.
4. Model Binding: Magically Mapping Requests to C# Objects
The Definition
Model Binding is the process where ASP.NET Core extracts data from the HTTP request (URL, Query String, Body, or Headers) and converts it into C# variables or objects that your action method expects.
The Problem
Without Model Binding, you would have to manually read the HttpRequest stream, parse the JSON string into an object, and cast data types (e.g., converting the string "42" to an integer). This is tedious and error-prone.
Imagination Exercise: Imagine trying to translate a letter written in French to English by looking up every single word in a dictionary, one by one. That is manual parsing. Model Binding is the "Universal Translator" that just hands you the English version immediately. 👽
The Solution
The [ApiController] attribute and the framework automatically bind data based on where it is found.
Common Binding Attributes
[FromBody]: Reads content from the JSON body of the request.[FromRoute]: Reads data from the URL path (e.g.,/api/gadgets/5).[FromQuery]: Reads data from the query string (e.g.,/api/gadgets?color=blue).
Practical Example
Let's define a Model (DTO - Data Transfer Object) first:
public class GadgetRequest
{
public string Name { get; set; }
public string Category { get; set; }
}Now, let's look at the Controller method:
// POST: api/gadgets
[HttpPost]
public IActionResult CreateGadget([FromBody] GadgetRequest newGadget)
{
// The framework has already:
// 1. Read the JSON body
// 2. Instantiated GadgetRequest
// 3. Mapped JSON properties to C# properties
if (string.IsNullOrEmpty(newGadget.Name))
{
return BadRequest("Name is required.");
}
// Pretend we saved it to a database...
return Ok($"Created {newGadget.Name} in category {newGadget.Category}");
}
// GET: api/gadgets/search?term=sonic
[HttpGet("search")]
public IActionResult Search([FromQuery] string term)
{
// Automatically pulls "term" from the URL query string
return Ok($"Searching for: {term}");
}Implicit Binding Sources
Because we used the [ApiController] attribute at the top of our class, ASP.NET Core is smart enough to guess:
- Complex types (classes) usually come from the Body.
- Simple types (int, string) usually come from the Route or Query.
You typically only need to add [FromBody] or [FromQuery] if you need to override this default behavior or want to be explicit for readability.
🧪 Industry Practice Summary
- Structure: Keep controllers clean. They should handle HTTP stuff (requests/responses). Do not write heavy business logic (calculations, database calls) directly in the controller; pass that to a Service class.
- Naming: Always end your class names with
Controller(e.g.,OrderController). - Async: In real-world apps, almost all controller methods should be
async Task<IActionResult>.
📚 References & Further Reading
- Create a Web API with ASP.NET Core Controllers (Official Docs)
- ControllerBase Class Reference
- Routing to Controller Actions
- Model Binding in ASP.NET Core
Proceed to the challenge. Define your routes clearly. 🖖
Challenge
You are tasked with building the API controller for managing a collection of Gadget objects. Your goal is to implement a full CRUD (Create, Read, Update, Delete) controller following ASP.NET Core conventions.
Requirements:
- Define a public class named
GadgetsController. - The class must inherit from
ControllerBase. - Decorate the class with the
[ApiController]attribute. - Add a class-level
[Route]attribute to set the base path to"api/[controller]". - Implement the following five public action methods:
- Get All Gadgets: A method that handles
GETrequests to the base route (/api/gadgets). It should be namedGetAlland return anIActionResult. - Get Gadget by ID: A method that handles
GETrequests to/{id}. It should be namedGetById, return anIActionResult, and accept an integeridfrom the route. - Create Gadget: A method that handles
POSTrequests to the base route. It should be namedCreate, return anIActionResult, and accept aGadgetobject from the request body. - Update Gadget: A method that handles
PUTrequests to/{id}. It should be namedUpdate, return anIActionResult, and accept an integeridfrom the route and aGadgetobject from the body. - Delete Gadget: A method that handles
DELETErequests to/{id}. It should be namedDelete, return anIActionResult, and accept an integeridfrom the route.
- Get All Gadgets: A method that handles
Use the appropriate HTTP verb and model binding attributes for each method. The method bodies can be left empty.
Expected result
Your solution should be a single C# file containing the GadgetsController class with all the required attributes and method signatures. The final code should look like this:
using Microsoft.AspNetCore.Mvc;
// A simple model for our API
public class Gadget
{
public int Id { get; set; }
public string? Name { get; set; }
}
[ApiController]
[Route("api/[controller]")]
public class GadgetsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll()
{
// Method body is not evaluated
return Ok();
}
[HttpGet("{id}")]
public IActionResult GetById([FromRoute] int id)
{
// Method body is not evaluated
return Ok();
}
[HttpPost]
public IActionResult Create([FromBody] Gadget gadget)
{
// Method body is not evaluated
return Ok();
}
[HttpPut("{id}")]
public IActionResult Update([FromRoute] int id, [FromBody] Gadget gadget)
{
// Method body is not evaluated
return Ok();
}
[HttpDelete("{id}")]
public IActionResult Delete([FromRoute] int id)
{
// Method body is not evaluated
return Ok();
}
}