An ASP.NET Core controller is a C# class that groups action methods handling related HTTP requests. Put shared routing rules, authorization requirements, or other settings on the class instead of repeating them on every action. For a web API that returns data rather than views, inherit from ControllerBase. section 1.2.3
Listing 2.4 BoardGamesController.cs file
using Microsoft.AspNetCore.Mvc;
namespace MyBGList.Controllers
{
[Route("[controller]")] #1
[ApiController]
public class BoardGamesController : ControllerBase
{
private readonly ILogger<BoardGamesController> _logger;
public BoardGamesController(ILogger<BoardGamesController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetBoardGames")] #2
public IEnumerable<BoardGame> Get()
{
return new[] {
new BoardGame() {
Id = 1,
Name = "Axis & Allies",
Year = 1981
},
new BoardGame() {
Id = 2,
Name = "Citadels",
Year = 2000
},
new BoardGame() {
Id = 3,
Name = "Terraforming Mars",
Year = 2016
}
};
}
}
}
BoardGamesController uses [Route("[controller]")] to establish its /BoardGames route. Its [HttpGet] action returns BoardGame objects, which become a JSON array in the response. The constructor also receives a logger. section 2.4.5
To replace the starter weather-forecast endpoint with a board-game endpoint:
- Create a BoardGame data class with Id, Name, and Year properties. section 2.4.5
- Replace WeatherForecastController with an empty API controller named BoardGamesController, then add a GET action that returns board-game data. section 2.4.5
- Request /BoardGames and check that the response is a JSON array. The initial three-game response is sample data, not database retrieval. section 2.4.5
A small endpoint can instead use Minimal APIs, which map routes without a separate controller class. Keeping a controller is useful as related actions grow more involved. Controller-based grouping also carries into SwaggerUI: Swashbuckle groups an action’s endpoint under its controller name. section 1.2.4 section 11.2.7







