עדכון באמצעות PUT
חלק מהיחידה Minimal APIs במסלול ה-ASP.NET Core של Coddy. שיעור 9 מתוך 20.
בקשת PUT מחליפה את המשאב בכתובת מסוימת בגוף שהיא שולחת. הלמבדה שלה מקבלת יחד פרמטר נתיב וגוף:
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 מחזירה את המיקום של ההתאמה הראשונה, או -1. אי אפשר לשנות רשומה לאחר יצירתה, ולכן נקודת הקצה יוצרת רשומה חדשה עם אותו מזהה ומציבה אותה במיקום הזה. שליחת אותה בקשת PUT פעמיים מניבה את אותה תוצאה; שליחת אותה בקשת POST פעמיים מוסיפה שני משאבים.
אתגר
קללקוחות יכולים לשנות מתכון.
- ב־
Program.cs, יש למפות אתPUT /api/recipes/{id:int}. הלמבדה שלו מקבלתint idואתNewRecipe input. - מוצאים את המיקום של המתכון באמצעות
recipes.FindIndex(r => r.Id == id). אם הערך הוא-1, מחזיריםResults.NotFound(new { error = $"Recipe {id} not found" }). - אחרת, יוצרים
new Recipe(id, input.Name, input.Category, input.Minutes), מציבים אותו במיקום הזה בתוךrecipesומחזיריםResults.Ok(recipe).
נסו זאת: לחצו על הרצה, בחרו PUT, הזינו את הנתיב /api/recipes/2, את גוף הבקשה {"name":"Banana Pancakes","category":"breakfast","minutes":20}, ולחצו על שליחה: הסטטוס יהיה 200 עם {"id":2,"name":"Banana Pancakes","category":"breakfast","minutes":20}. שלחו GET /api/recipes: שלושה מתכונים, כש־Banana Pancakes נמצא באמצע. בקשת PUT אל /api/recipes/99 מחזירה 404.
נסו בעצמכם
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();