Cập nhật bằng PUT
Thuộc phần Minimal API trong hành trình ASP.NET Core của Coddy. Bài học 9 trên 20.
Yêu cầu PUT thay thế tài nguyên tại một địa chỉ bằng nội dung gửi đi. Hàm lambda nhận đồng thời một tham số tuyến đường và một nội dung:
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 trả về vị trí của kết quả khớp đầu tiên hoặc -1. Không thể thay đổi bản ghi sau khi tạo, vì vậy endpoint tạo một bản ghi mới có cùng id rồi đặt nó vào vị trí đó. Gửi cùng một yêu cầu PUT hai lần sẽ cho cùng một kết quả; gửi cùng một yêu cầu POST hai lần sẽ thêm hai tài nguyên.
Thử thách
DễMáy khách có thể thay đổi công thức nấu ăn.
- Trong
Program.cs, ánh xạPUT /api/recipes/{id:int}. Lambda của nó nhậnint idvàNewRecipe input. - Tìm vị trí của công thức bằng
recipes.FindIndex(r => r.Id == id). Nếu vị trí là-1, trả vềResults.NotFound(new { error = $"Recipe {id} not found" }). - Nếu không, tạo
new Recipe(id, input.Name, input.Category, input.Minutes), đặt nó vào vị trí đó trongrecipesrồi trả vềResults.Ok(recipe).
Thử nhé: nhấn Chạy, chọn PUT, đường dẫn /api/recipes/2, phần thân {"name":"Banana Pancakes","category":"breakfast","minutes":20} rồi nhấn Gửi: nhận trạng thái 200 cùng {"id":2,"name":"Banana Pancakes","category":"breakfast","minutes":20}. Gửi GET /api/recipes: có ba công thức nấu ăn, với Banana Pancakes ở giữa. PUT đến /api/recipes/99 trả về 404.
Tự làm thử
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();
Tất cả bài học trong Minimal API
1Các endpoint đầu tiên
Endpoint đầu tiên của bạnTrả về JSON2Kết quả và phần thân JSON
OK và không tìm thấy