A shop can't write a route for each of its products. Instead, one route has a placeholder in its path: a path parameter, written in braces. In /products/{id:int}, the placeholder matches whatever is written in that place, so /products/3 matches with id equal to 3. ASP.NET passes the value to your function, as a parameter with the same name: (int id) =>.
The :int part is a route constraint: it matches only whole numbers. A path like /products/mug doesn't match, so it gets 404, and /products/count still goes to its own route. Here is the same idea on another route:
app.MapGet("/square/{number:int}", (int number) => {
return Results.Json(new { square = number * number });
});
Once you have the id, find the product with a foreach loop: check each product's "id", and when it equals id, return that product. A product's values are stored as object, so write (int)product["id"] to compare it as a number. return ends the function, so the loop stops there. C# needs every way through the function to return something, so after the loop, return Results.NotFound(): no product had that id.
Your app must answer:
GET /products/1 → 200 {"id": 1, "name": "Mug", "price": 12, "category": "kitchen"}
GET /products/3 → 200 {"id": 3, "name": "Lamp", "price": 29, "category": "home"}
GET /products/4 → 200 {"id": 4, "name": "Pen", "price": 2, "category": "office"}
GET /products/count → 200 {"count": 4}
GET /products/mug → 404 (empty body)
Your task: add a route with app.MapGet for /products/{id:int}, whose function takes int id, loops over products, and returns, as JSON, the product whose "id" equals id; after the loop, it returns Results.NotFound().
Assignment
Follow the Coding Tutorial to add the route that answers one product by its id.
Hint
The name inside the braces of the path and the function's parameter must be the same, id. Inside the loop, compare (int)product["id"] with id.
Free plan: 30 tutor messages. PRO is unlimited.
