Route Parameters
Part of the Minimal APIs section of Coddy's ASP.NET Core journey. Lesson 3 of 20.
One route per recipe would never end. A route parameter is a part of the path in braces: it matches any value in that place.
app.MapGet("/orders/{number}", (int number) => $"Order {number}");GET /orders/42 answers Order 42. ASP.NET Core passes the value to the lambda parameter with the same name, and converts the text 42 to the parameter's type, here int. A parameter whose name is not in the route is looked for in the query string instead, and when it is not there either, the answer is 400 Bad Request. A status code is the number at the start of every response: 200 means OK, and codes from 400 to 499 mean the request was wrong.
Challenge
EasyEach recipe gets its own address: /api/recipes/1, /api/recipes/2 and so on.
- In
Program.cs, belowGET /api/recipes, mapGET /api/recipes/{id}. - Its lambda takes
int idand returns the recipe whoseIdequalsid.recipes.FirstOrDefault(r => r.Id == id)finds it.
Try it: press Run. GET /api/recipes/2 answers {"id":2,"name":"Pancakes","category":"breakfast","minutes":15}. Send GET /api/recipes/99: no recipe has that id, so FirstOrDefault returns null and the answer is status 200 with the body null. The next chapter answers 404 for it.
Try it yourself
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var recipes = new List<Recipe>
{
new(1, "Tomato Soup", "soup", 25),
new(2, "Pancakes", "breakfast", 15),
new(3, "Lentil Soup", "soup", 40),
};
app.MapGet("/", () => "Recipe API is running");
app.MapGet("/api/recipes", () => recipes);
app.Run();
All lessons in Minimal APIs
2Results and JSON Bodies
Ok and Not Found