Menu
CoddyTech

路由约束

本课属于 Coddy ASP.NET Core 学习旅程的“Minimal APIs”单元。第 4 课,共 20 课。

GET /orders/abc 匹配 /orders/{number},然后无法将 abc 转换为 int:400 错误请求。冒号后面的路由约束会限制参数的匹配范围,因此该路径不匹配任何路由,返回 404 未找到。

app.MapGet("/orders/{number:int}", (int number) => $"Order {number}");
app.MapGet("/orders/{code:alpha}", (string code) => $"Code {code}");

:int 匹配整数,:alpha 匹配字母,因此 /orders/7 和 /orders/abc 各自会匹配一条路由。其他约束还有 :guid、:min(1) 和 :length(3),它们可以组合使用:{number:int:min(1)}。约束用于选择路由,不用于检查用户的输入,因为被拒绝的值会返回 404,而不是 400。

challenge icon

挑战

简单

GET /api/recipes/abc 会因绑定 int id 出错而返回 400。这个地址永远不会对应任何食谱,所以应该返回 404。

  1. 在 Program.cs 中,将上一课的端点路由改为 /api/recipes/{id:int}。
  2. 只保留一条路由:修改现有行,不要再添加一条。

试试看:按“运行”:GET /api/recipes/2 仍会返回 Pancakes 食谱。发送 GET /api/recipes/abc:状态码为 404,响应正文为空。Routes 列表中会显示 GET /api/recipes/{id:int}。

亲手试试

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();
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

Minimal APIs中的所有课