Controllers and Actions
Level: Beginner to Intermediate
Controllers organize API endpoints into classes. This is the bridge between ASP.NET Core fundamentals and full Web API development.
- Controller definition: Class that handles HTTP requests and returns responses
ControllerBasevsController: ControllerBase for APIs (returns JSON), Controller for MVC (returns HTML views)[ApiController]attribute: Auto-validates input, binds body from JSON, returns problem details on error[Route]attribute: Defines URL pattern for all actions in controller ([Route("api/students")])[HttpGet],[HttpPost],[HttpPut],[HttpDelete]: Map action to HTTP method- Action method examples: HttpGet with route parameter captures ID from URL and passes to action method
- Dependency injection in controllers: Constructor receives services (
public StudentsController(IStudentService service)) - Controller action flow: Receive request → Parse parameters → Call service → Return response
- School Management controller design: StudentsController with GetAll, GetById, Create, Update, Delete actions
- Returning results:
Ok(student)(200),Created("route", student)(201),BadRequest()(400),NotFound()(404) - Route parameters: Route values like id are captured from URL path and passed as action parameters
- Query parameters: GetStudents action method accepts optional className and status query parameters for filtering
- Model binding: StudentController receives Student object with name, rollNumber, className automatically from JSON body
- Common controller mistakes: Forgetting AddControllers(), putting business logic in actions, using Controller instead of ControllerBase for APIs
What is a Controller?
A controller is a C# class that groups related HTTP endpoints.
Example:
StudentsController -> student-related endpoints
TeachersController -> teacher-related endpoints
AttendanceController -> attendance-related endpoints
FeesController -> fee-related endpoints
Instead of placing all routes in Program.cs, controllers keep code organized.
What is an Action?
An action is a public method inside a controller that handles one HTTP request.
Example:
[HttpGet("{id}")]
public IActionResult GetStudent(int id)
{
return Ok();
}
This action handles:
GET /api/students/101
Minimal APIs vs Controllers
| Feature | Minimal APIs | Controllers |
|---|---|---|
| Best for | Small APIs, quick demos | Medium and large APIs |
| Organization | Routes in Program.cs or grouped extensions | Class-based |
| Attributes | Less required | Commonly used |
| Filters | Limited compared to MVC | Strong support |
| Web API projects | Good | Very common |
For learning backend development, controllers are important because many real enterprise projects use them.
Enable Controllers
In Program.cs:
Two important lines:
builder.Services.AddControllers();
app.MapControllers();
Without these, controller routes will not work.
Basic Controller Structure
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/students")]
public class StudentsController : ControllerBase
{
[HttpGet]
public IActionResult GetAllStudents()
{
return Ok(new[]
{
new { Id = 101, Name = "Anika" },
new { Id = 102, Name = "Rahul" }
});
}
}
Route:
GET /api/students
Important Controller Parts
| Part | Meaning |
|---|---|
[ApiController] | Enables API-specific behavior like automatic model validation |
[Route("api/students")] | Base route for the controller |
ControllerBase | Base class for Web API controllers |
[HttpGet] | Maps action to HTTP GET |
IActionResult | Allows returning different HTTP responses |
ControllerBase vs Controller
Use ControllerBase for Web APIs.
Use Controller for MVC views.
| Base Class | Use Case |
|---|---|
ControllerBase | APIs returning JSON |
Controller | MVC apps returning Razor views |
For backend APIs, choose:
public class StudentsController : ControllerBase
Route Attributes
Base route:
[Route("api/students")]
Action route:
[HttpGet("{id}")]
Combined route:
GET /api/students/101
Common HTTP Method Attributes
| Attribute | HTTP Method | Common Use |
|---|---|---|
[HttpGet] | GET | Read data |
[HttpPost] | POST | Create data |
[HttpPut] | PUT | Replace/update data |
[HttpPatch] | PATCH | Partial update |
[HttpDelete] | DELETE | Delete data |
Full Student Controller Example
[ApiController]
[Route("api/students")]
public class StudentsController : ControllerBase
{
private readonly IStudentService _studentService;
private readonly ILogger<StudentsController> _logger;
public StudentsController(
IStudentService studentService,
ILogger<StudentsController> logger)
{
_studentService = studentService;
_logger = logger;
}
[HttpGet]
public IActionResult GetAllStudents()
{
var students = _studentService.GetAllStudents();
return Ok(students);
}
[HttpGet("{id}")]
public IActionResult GetStudent(int id)
{
var student = _studentService.GetStudent(id);
if (student == null)
{
_logger.LogWarning("Student {StudentId} not found", id);
return NotFound();
}
return Ok(student);
}
[HttpPost]
public IActionResult CreateStudent(CreateStudentRequest request)
{
var student = _studentService.CreateStudent(request);
return CreatedAtAction(
nameof(GetStudent),
new { id = student.Id },
student);
}
[HttpPut("{id}")]
public IActionResult UpdateStudent(int id, UpdateStudentRequest request)
{
var updated = _studentService.UpdateStudent(id, request);
if (!updated)
{
return NotFound();
}
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeleteStudent(int id)
{
var deleted = _studentService.DeleteStudent(id);
if (!deleted)
{
return NotFound();
}
return NoContent();
}
}
Resulting API Routes
| Request | Action |
|---|---|
GET /api/students | GetAllStudents() |
GET /api/students/101 | GetStudent(101) |
POST /api/students | CreateStudent(...) |
PUT /api/students/101 | UpdateStudent(101, ...) |
DELETE /api/students/101 | DeleteStudent(101) |
Request DTOs
Request DTOs represent input data.
public class CreateStudentRequest
{
public string Name { get; set; } = string.Empty;
public string Grade { get; set; } = string.Empty;
public DateTime DateOfBirth { get; set; }
}
Avoid accepting database entities directly from API requests.
Controller Naming
ASP.NET Core convention:
StudentsController
TeachersController
AttendanceController
The class should end with Controller.
With route:
[Route("api/[controller]")]
StudentsController becomes:
api/students
Many teams prefer explicit routes:
[Route("api/students")]
Explicit routes are easier for beginners.
Common Mistakes
| Mistake | Better Approach |
|---|---|
Forgetting AddControllers() | Add it in Program.cs |
Forgetting MapControllers() | Add it before app.Run() |
| Putting business logic directly in actions | Move logic into services |
| Returning only strings from APIs | Return proper results and DTOs |
Using Controller for APIs | Use ControllerBase |
| Making routes inconsistent | Follow REST-style route naming |
Practice Task
Create a TeachersController.
- Add
[ApiController]. - Add
[Route("api/teachers")]. - Create
GET /api/teachers. - Create
GET /api/teachers/{id}. - Inject
ILogger<TeachersController>. - Return
NotFound()when a teacher does not exist.
Quick Recap
| Question | Answer |
|---|---|
| What is a controller? | Class that groups related endpoints |
| What is an action? | Method that handles one HTTP request |
| API base class? | ControllerBase |
| Enables API behavior? | [ApiController] |
| Maps controllers? | app.MapControllers() |
Q: What are controllers and actions in ASP.NET Core?
Good Answer: "A controller is a class that groups related API endpoints, and an action is a public method inside the controller that handles a specific HTTP request. Controllers commonly use attributes such as [ApiController], [Route], [HttpGet], and [HttpPost] to define routing. For Web APIs, controllers usually inherit from ControllerBase. Controllers help organize large applications and use dependency injection to access services, logging, and configuration."
Use ChatGPT, Claude, or Copilot to go deeper on ASP.NET Core Controllers. Try these prompts:
"Explain controllers and actions with a school API example.""What is the difference between ControllerBase and Controller?""Why do we need AddControllers and MapControllers?""Show me a REST-style controller for students."
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.