Menu
CoddyTech

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.

challenge icon

Thử thách

Dễ

Máy khách có thể thay đổi công thức nấu ăn.

  1. Trong Program.cs, ánh xạ PUT /api/recipes/{id:int}. Lambda của nó nhận int id và NewRecipe input.
  2. 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" }).
  3. Nếu không, tạo new Recipe(id, input.Name, input.Category, input.Minutes), đặt nó vào vị trí đó trong recipes rồ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