Menu
CoddyTech

정상 응답과 찾을 수 없음

Coddy ASP.NET Core 여정의 Minimal API 섹션에 포함된 레슨. 20개 중 6번째.

여러 방식으로 응답할 수 있는 엔드포인트는 상태 코드를 설정하는 Results에서 결과를 반환합니다. Results.Ok(value)는 값이 JSON으로 포함된 200 응답이고, Results.NotFound()는 존재하지 않는 항목에 사용하는 코드인 404 찾을 수 없음 응답입니다.

app.MapGet("/books/{id:int}", (int id) =>
{
    var book = books.FirstOrDefault(b => b.Id == id);
    if (book is null)
        return Results.NotFound(new { error = "No such book" });
    return Results.Ok(book);
});

모든 return이 Results를 거치므로 같은 형식인 IResult를 공유하며, 람다가 컴파일됩니다. new { error = "No such book" }는 익명 객체입니다. ASP.NET Core는 이를 {"error":"No such book"}로 작성하며, 이 본문은 클라이언트에 무엇이 잘못되었는지 알려 줍니다.

challenge icon

챌린지

쉬움

GET /api/recipes/99는 null과 함께 200을 반환합니다. 클라이언트는 이 응답으로 레시피가 존재하지 않는다는 것을 알 수 없으므로, 404를 반환해야 합니다.

  1. Program.cs에서 GET /api/recipes/{id:int} 람다에 { ... } 블록 본문을 작성하고, FirstOrDefault로 레시피를 찾으세요.
  2. 레시피가 null이면 Results.NotFound(new { error = $"Recipe {id} not found" })를 반환하세요. id가 99이면 본문은 {"error":"Recipe 99 not found"}입니다.
  3. 그렇지 않으면 Results.Ok(recipe)를 반환하세요.

직접 해 보기: 실행을 누르세요. GET /api/recipes/99는 상태 코드 404와 함께 {"error":"Recipe 99 not found"}를 반환합니다. GET /api/recipes/2를 보내세요. 이전처럼 상태 코드 200과 Pancakes 레시피가 반환됩니다.

직접 해보기

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) => recipes.FirstOrDefault(r => r.Id == id));

app.Run();

Minimal API의 모든 레슨