PUT으로 업데이트하기
Coddy ASP.NET Core 여정의 Minimal API 섹션에 포함된 레슨. 20개 중 9번째.
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을 반환합니다. 레코드는 생성된 후 변경할 수 없으므로, 엔드포인트는 동일한 id를 가진 새 레코드를 만들어 해당 위치에 넣습니다. 같은 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가 표시됩니다. /api/recipes/99로 PUT 요청을 보내면 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();