读取 JSON 请求体
本课属于 Coddy ASP.NET Core 学习旅程的“Minimal APIs”单元。第 7 课,共 20 课。
POST 请求会在 body 中发送数据,通常采用 JSON 格式。当 POST lambda 接收一个记录参数时,ASP.NET Core 会将请求正文作为 JSON 读取到该参数中,属性名不区分大小写。
app.MapPost("/notes", (NewNote input) =>
{
var note = new Note(notes.Count + 1, input.Text);
notes.Add(note);
return Results.Created($"/notes/{note.Id}", note);
});Results.Created 会返回 201 Created,这是新资源对应的状态码,同时会在 Location 标头中提供资源地址,并将资源放在请求正文中。如果值的类型不正确,例如 "text": 5,请求会在 lambda 运行前返回 400。JSON 中缺少的属性会使用默认值:null 或 0。在笔记本电脑上,curl 使用 -d 发送请求正文;这里的请求栏中有一个 Body 框。
挑战
简单客户端可以添加菜谱。它们发送除 id 以外的所有内容,API 会分配下一个 id。
- 在
Recipe.cs中,添加record NewRecipe(string Name, string Category, int Minutes);。 - 在
Program.cs中的列表下方,添加var nextId = 4;。 - 映射
POST /api/recipes。它的 lambda 接收NewRecipe input,创建new Recipe(nextId++, input.Name, input.Category, input.Minutes),并将其添加到recipes中。 - 返回
Results.Created($"/api/recipes/{recipe.Id}", recipe)。
试试看:按“运行”,选择 POST,输入路径 /api/recipes 和请求体 {"name":"Waffles","category":"breakfast","minutes":20},然后按“发送”。答案是状态码 201,响应内容为 {"id":4,"name":"Waffles","category":"breakfast","minutes":20},而 Headers 标签页会显示 Location: /api/recipes/4。发送 GET /api/recipes/4:Waffles。每次按“发送”都会在一个全新的应用中重放你之前发送的 POST 请求,所以菜谱仍然在那里。再次发送 POST 请求:id 为 5。
亲手试试
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", (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.Run();
这节课包含一个小测验。开始学习即可作答,并记录你的进度。