Menu
CoddyTech

JSON Gövdesini Okuma

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

Bir POST isteği verileri gövdesinde, genellikle JSON olarak gönderir. Bir POST lambda'sı kayıt parametresi aldığında, ASP.NET Core gövdeyi JSON olarak okuyup bu parametreye aktarır ve adları büyük-küçük harf farkı gözetmeden eşleştirir.

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, yeni bir kaynak için kullanılan durum kodu olan 201 Created yanıtını; adresini içeren bir Location başlığı ve gövdede kaynakla birlikte döndürür. "text": 5 gibi yanlış türdeki bir değer, lambda çalışmadan önce 400 yanıtına yol açar. JSON'da yer almayan bir özellik varsayılan değerini alır: null veya 0. Bir dizüstü bilgisayarda curl, -d ile gövde gönderir; burada istek çubuğunda bir Body kutusu bulunur.

challenge icon

Görev

Kolay

İstemciler tarif ekleyebilir. id dışında her şeyi gönderirler ve API bir sonraki id değerini belirler.

  1. Recipe.cs dosyasına record NewRecipe(string Name, string Category, int Minutes); ekle.
  2. Program.cs dosyasında, listenin altına var nextId = 4; ekle.
  3. POST /api/recipes eşlemesini yap. Lambda, NewRecipe input alır, new Recipe(nextId++, input.Name, input.Category, input.Minutes) oluşturur ve bunu recipes listesine ekler.
  4. Results.Created($"/api/recipes/{recipe.Id}", recipe) döndür.

Dene: Çalıştır'a bas, POST'u seç, yol olarak /api/recipes yaz ve gövdeye {"name":"Waffles","category":"breakfast","minutes":20} gir, ardından “Gönder”e bas. Yanıt, durum kodu 201 ve {"id":4,"name":"Waffles","category":"breakfast","minutes":20} olur; Headers sekmesinde Location: /api/recipes/4 görünür. GET /api/recipes/4 isteğini gönder: Waffles. Her “Gönder” işlemi, önceki POST isteklerini yeni bir uygulamada yeniden çalıştırır; bu yüzden tarif hâlâ oradadır. POST isteğini tekrar gönder: id 5.

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),
};

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();
quiz iconKendini test et

Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.

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