Building a Web API
This lesson pulls together routing, controllers, model binding, and Entity Framework from the earlier lessons into one small, real REST API for managing products.
The full controller
C# Controllers/ProductsController.cs
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly AppDbContext _db;
public ProductsController(AppDbContext db) => _db = db;
[HttpGet]
public IActionResult GetAll() =>
Ok(_db.Products.ToList());
[HttpGet("{id:int}")]
public IActionResult GetById(int id)
{
var product = _db.Products.Find(id);
return product is null ? NotFound() : Ok(product);
}
[HttpPost]
public IActionResult Create([FromBody] Product product)
{
_db.Products.Add(product);
_db.SaveChanges();
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}
[HttpDelete("{id:int}")]
public IActionResult Delete(int id)
{
var product = _db.Products.Find(id);
if (product is null) return NotFound();
_db.Products.Remove(product);
_db.SaveChanges();
return NoContent();
}
}
Exercising every route
Terminal
curl -X POST http://localhost:5225/api/products \
-H "Content-Type: application/json" \
-d '{"name":"Headphones","price":59.99}'
curl http://localhost:5225/api/products
curl http://localhost:5225/api/products/1
curl -X DELETE http://localhost:5225/api/products/1
curl -i http://localhost:5225/api/products/1
Output
{"id":1,"name":"Headphones","price":59.99}
[{"id":1,"name":"Headphones","price":59.99}]
{"id":1,"name":"Headphones","price":59.99}
(204 No Content)
HTTP/1.1 404 Not FoundCreatedAtAction returns a 201 response with a Location header pointing back at the new resource's GetById URL — the correct REST convention for a successful creation, rather than just returning a plain 200. NoContent() is the equally conventional response for a successful delete: the operation worked, and there's nothing left to send back.
Course complete: that covers the ASP.NET Core fundamentals — running a project with the minimal API style, routing requests by method and path, organizing endpoints into controllers, mixing C# into HTML with Razor, binding and validating request data into models, understanding the middleware pipeline requests flow through, and querying a real database with Entity Framework Core. Together these pieces are the shape of most real-world ASP.NET APIs — the next natural steps are authentication (JWT tokens or cookie auth), deploying to a real host, and exploring Blazor if you want to build UI in C# as well.