路由组
本课属于 Coddy ASP.NET Core 学习旅程的“Minimal APIs”单元。第 11 课,共 20 课。
同一资源的各个端点,其路由开头相同。app.MapGroup(prefix) 会创建一个路由组:映射到该组的每个端点,都会在自己的模式前加上此前缀。
var orders = app.MapGroup("/api/orders");
orders.MapGet("/", () => orderList);
orders.MapGet("/{id:int}", (int id) => orderList.FirstOrDefault(o => o.Id == id));
orders.MapDelete("/{id:int}", (int id) => orderList.RemoveAll(o => o.Id == id));这些路由分别是 /api/orders/、/api/orders/{id:int},以及使用相同模式的 DELETE 路由。GET /api/orders 会匹配 /api/orders/,因为末尾的斜杠不会改变匹配的路由。前缀只需写一次,因此重命名时只需修改一行,而且路由组可以将设置应用到其中的所有端点,例如要求用户登录。在组内再次写入前缀会导致前缀重复:/api/orders/api/orders/{id:int}。
挑战
简单学习者可以收藏喜欢的食谱。这 3 个收藏端点共用一个组。
- 在
Program.cs中的nextId下方,添加var favoriteIds = new List<int>();。 - 在
app.Run()上方创建这个组:var favorites = app.MapGroup("/api/favorites");。 - 在这个组上映射 GET
"/":按recipes中的顺序,返回Id在favoriteIds中的食谱。 - 映射 POST
"/{id:int}":如果没有食谱的 ID 与该 ID 相同,则返回Results.NotFound(new { error = $"Recipe {id} not found" })。否则,如果favoriteIds中还没有该 ID,就添加它,然后返回Results.NoContent()。 - 映射 DELETE
"/{id:int}":从favoriteIds中移除该 ID,然后返回Results.NoContent()。
试一试:按“运行”:GET /api/favorites 返回 []。发送空请求体的 POST /api/favorites/2:状态码为 204。发送 GET /api/favorites:返回一个包含 Pancakes 食谱的列表。POST /api/favorites/99 返回 404,DELETE /api/favorites/2 会再次清空列表。
亲手试试
using Microsoft.AspNetCore.Http.HttpResults;
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),
};
var nextId = 4;
app.MapGet("/", () => "Recipe API is running");
app.MapGet("/api/recipes", (string? category) =>
recipes.Where(r => category is null || r.Category == category));
app.MapGet("/api/recipes/{id:int}", (int id) =>
{
var recipe = recipes.FirstOrDefault(r => r.Id == id);
if (recipe is null)
return Results.NotFound(new { error = $"Recipe {id} not found" });
return Results.Ok(recipe);
});
app.MapPost("/api/recipes", (NewRecipe input) =>
{
if (string.IsNullOrWhiteSpace(input.Name))
return Results.BadRequest(new { error = "Name is required" });
if (input.Minutes <= 0)
return Results.BadRequest(new { error = "Minutes must be more than 0" });
var recipe = new Recipe(nextId++, input.Name, input.Category, input.Minutes);
recipes.Add(recipe);
return Results.Created($"/api/recipes/{recipe.Id}", recipe);
});
app.MapPut("/api/recipes/{id:int}", (int id, NewRecipe input) =>
{
var index = recipes.FindIndex(r => r.Id == id);
if (index == -1)
return Results.NotFound(new { error = $"Recipe {id} not found" });
var recipe = new Recipe(id, input.Name, input.Category, input.Minutes);
recipes[index] = recipe;
return Results.Ok(recipe);
});
app.MapDelete("/api/recipes/{id:int}", Results<NoContent, NotFound> (int id) =>
{
var removed = recipes.RemoveAll(r => r.Id == id);
return removed > 0 ? TypedResults.NoContent() : TypedResults.NotFound();
});
app.Run();
这节课包含一个小测验。开始学习即可作答,并记录你的进度。