Tutorials ASP.NET Core Web API Tutorial
Download and Install Visual Studio 2022 — Complete Guide
Download and Install Visual Studio 2022 — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of ASP.NET Core Web API Tutorial on Toolliyo Academy.
On this page
ASP.NET Core Web API Tutorial · Lesson 5 of 100
Controllers in ASP.NET Core Web API
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — API foundations · ~6 min · Module 1: Web API Fundamentals
What is this?
A controller is a class that handles HTTP requests. It inherits ControllerBase (not Controller — that is for MVC views). Methods are actions. Attributes like [HttpGet] and [Route] define URLs.
Why should you care?
Controllers are the front door of your API. Keep them thin: validate input, call a service, return a DTO. Fat controllers with SQL inside are hard to test and maintain.
See it live — copy this example
Create a Web API (dotnet new webapi), paste the example, run dotnet run, test in Swagger.
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id:int}")]
public ActionResult<ProductDto> Get(int id)
=> Ok(new ProductDto(id, "Demo Product", 99m));
}
Run Example »
Edit the code and click Run — like W3Schools Try it Yourself.
What happened?
- [ApiController] enables automatic model validation and binding rules.
- [Route("api/[controller]")] makes the URL /api/products for ProductsController.
- Inject services via constructor — ASP.NET creates them using DI.
Try it yourself
- Add Controllers/ProductsController.cs to ShopNest.API.
- Add [ApiController] and [Route("api/[controller]")].
- Add one GET action returning a hard-coded ProductDto.
- Change a route URL or DTO property and save — test again in Swagger or curl.
- Return the wrong status code on purpose (404 instead of 200) and see what the client shows.
Remember
ControllerBase + [ApiController] for JSON APIs. One controller per resource group (Products, Orders). Inject services; do not new() up DbContext in actions.