使用 PUT 更新
本课属于 Coddy ASP.NET Core 学习旅程的“Minimal APIs”单元。第 9 课,共 20 课。
PUT 请求会用请求正文替换指定地址上的资源。它的 lambda 会同时接收一个路由参数和一个请求正文:
app.MapPut("/notes/{id:int}", (int id, NewNote input) =>
{
var index = notes.FindIndex(n => n.Id == id);
if (index == -1)
return Results.NotFound();
notes[index] = new Note(id, input.Text);
return Results.Ok(notes[index]);
});FindIndex 会返回第一个匹配项的位置,如果没有匹配项,则返回 -1。记录创建后无法更改,因此这个端点会创建一个 id 相同的新记录,并将它放到该位置。连续发送两次相同的 PUT 请求会得到相同的结果;连续发送两次相同的 POST 请求则会添加两个资源。
挑战
简单客户端可以更改食谱。
- 在
Program.cs中映射PUT /api/recipes/{id:int}。它的 lambda 接收int id和NewRecipe input。 - 使用
recipes.FindIndex(r => r.Id == id)查找食谱的位置。如果结果是-1,则返回Results.NotFound(new { error = $"Recipe {id} not found" })。 - 否则,创建
new Recipe(id, input.Name, input.Category, input.Minutes),将它放到recipes中的该位置,然后返回Results.Ok(recipe)。
试试看:按“运行”,选择 PUT,路径为 /api/recipes/2,请求体为 {"name":"Banana Pancakes","category":"breakfast","minutes":20},然后点击“发送”:状态码为 200,返回 {"id":2,"name":"Banana Pancakes","category":"breakfast","minutes":20}。发送 GET /api/recipes:会有 3 个食谱,Banana Pancakes 位于中间。向 /api/recipes/99 发送 PUT 请求会返回 404。
亲手试试
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.Run();