Menu
CoddyTech

PUT ile Güncelleme

Coddy'nin ASP.NET Core Journey'sinin Minimal API'ler bölümünün bir parçası. Ders 9 / 20.

Bir PUT isteği, gönderdiği gövdeyle bir adresteki kaynağın yerini alır. Lambda işlevi bir rota parametresini ve bir gövdeyi birlikte alır:

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, ilk eşleşmenin konumunu veya -1 değerini döndürür. Bir kayıt oluşturulduktan sonra değiştirilemez; bu nedenle uç nokta aynı id ile yeni bir kayıt oluşturur ve onu o konuma koyar. Aynı PUT isteğini iki kez göndermek aynı sonucu verir; aynı POST isteğini iki kez göndermekse iki kaynak ekler.

challenge icon

Görev

Kolay

İstemciler bir tarifi değiştirebilir.

  1. Program.cs içinde PUT /api/recipes/{id:int} eşlemesini yap. Lambda’sı int id ve NewRecipe input alır.
  2. Tarifin konumunu recipes.FindIndex(r => r.Id == id) ile bul. Değer -1 olduğunda Results.NotFound(new { error = $"Recipe {id} not found" }) döndür.
  3. Aksi takdirde new Recipe(id, input.Name, input.Category, input.Minutes) oluştur, bunu recipes içindeki o konuma yerleştir ve Results.Ok(recipe) döndür.

Deneyin: Çalıştır'a bas, PUT'u seç, yol olarak /api/recipes/2, gövde olarak {"name":"Banana Pancakes","category":"breakfast","minutes":20} gir ve Gönder'e bas: {"id":2,"name":"Banana Pancakes","category":"breakfast","minutes":20} ile durum 200. GET /api/recipes isteğini gönder: üç tarif döner ve Banana Pancakes ortadadır. /api/recipes/99 adresine yapılan PUT isteği 404 yanıtı verir.

Kendin dene

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();

Minimal API'ler bölümündeki tüm dersler