Route Constraints
Part of the Minimal APIs section of Coddy's ASP.NET Core journey. Lesson 4 of 20.
GET /orders/abc matches /orders/{number}, then fails to convert abc to an int: 400 Bad Request. A route constraint after a colon limits what a parameter matches, so that path matches no route and answers 404 Not Found.
app.MapGet("/orders/{number:int}", (int number) => $"Order {number}");
app.MapGet("/orders/{code:alpha}", (string code) => $"Code {code}");:int matches whole numbers and :alpha matches letters, so /orders/7 and /orders/abc each reach one route. Others are :guid, :min(1) and :length(3), and they chain: {number:int:min(1)}. Constraints choose a route; they do not check a user's input, because a refused value answers 404, not 400.
Challenge
EasyGET /api/recipes/abc answers 400 with an error about binding int id. No recipe will ever have that address, so it should answer 404.
- In
Program.cs, change the route of the endpoint from the last lesson to/api/recipes/{id:int}. - Keep one route for it: change the existing line, do not add a second one.
Try it: press Run: GET /api/recipes/2 still answers the Pancakes recipe. Send GET /api/recipes/abc: status 404 and an empty body. The Routes list shows GET /api/recipes/{id:int}.
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.MapGet("/api/recipes/{id}", (int id) => recipes.FirstOrDefault(r => r.Id == id));
app.Run();
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Minimal APIs
2Results and JSON Bodies
Ok and Not Found