Skip to main content

Controllers and Actions

Level: Beginner to Intermediate

ℹ️ Where This Fits

Controllers organize API endpoints into classes. This is the bridge between ASP.NET Core fundamentals and full Web API development.

ℹ️ What You'll Learn
  • Controller definition: Class that handles HTTP requests and returns responses
  • ControllerBase vs Controller: 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

FeatureMinimal APIsControllers
Best forSmall APIs, quick demosMedium and large APIs
OrganizationRoutes in Program.cs or grouped extensionsClass-based
AttributesLess requiredCommonly used
FiltersLimited compared to MVCStrong support
Web API projectsGoodVery common

For learning backend development, controllers are important because many real enterprise projects use them.

Enable Controllers

In Program.cs:

💻 Try It — Console App
💡 Controllers need AddControllers and MapControllers.⌥ GitHub
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

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

PartMeaning
[ApiController]Enables API-specific behavior like automatic model validation
[Route("api/students")]Base route for the controller
ControllerBaseBase class for Web API controllers
[HttpGet]Maps action to HTTP GET
IActionResultAllows returning different HTTP responses

ControllerBase vs Controller

Use ControllerBase for Web APIs.

Use Controller for MVC views.

Base ClassUse Case
ControllerBaseAPIs returning JSON
ControllerMVC 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

AttributeHTTP MethodCommon Use
[HttpGet]GETRead data
[HttpPost]POSTCreate data
[HttpPut]PUTReplace/update data
[HttpPatch]PATCHPartial update
[HttpDelete]DELETEDelete 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

RequestAction
GET /api/studentsGetAllStudents()
GET /api/students/101GetStudent(101)
POST /api/studentsCreateStudent(...)
PUT /api/students/101UpdateStudent(101, ...)
DELETE /api/students/101DeleteStudent(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

MistakeBetter Approach
Forgetting AddControllers()Add it in Program.cs
Forgetting MapControllers()Add it before app.Run()
Putting business logic directly in actionsMove logic into services
Returning only strings from APIsReturn proper results and DTOs
Using Controller for APIsUse ControllerBase
Making routes inconsistentFollow REST-style route naming

Practice Task

Create a TeachersController.

  1. Add [ApiController].
  2. Add [Route("api/teachers")].
  3. Create GET /api/teachers.
  4. Create GET /api/teachers/{id}.
  5. Inject ILogger<TeachersController>.
  6. Return NotFound() when a teacher does not exist.

Quick Recap

QuestionAnswer
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()
🎯 Interview Favourite

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 AI to Learn Faster

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.

Next Article

-> Action Results - IActionResult

nexcoding.in