잘못된 요청
Coddy ASP.NET Core 여정의 Minimal API 섹션에 포함된 레슨. 20개 중 8번째.
본문에서 속성을 생략할 수 있습니다. {}는 바인딩되며, 레코드에 string이라고 되어 있어도 input.Email은 null입니다. nullable 참조 형식은 코드를 컴파일할 때만 경고를 표시하며 JSON은 검사하지 않습니다. 따라서 엔드포인트는 값을 직접 확인하고, 아무것도 변경하기 전에 Results.BadRequest로 400 Bad Request를 응답합니다.
app.MapPost("/signups", (Signup input) =>
{
if (string.IsNullOrWhiteSpace(input.Email))
return Results.BadRequest(new { error = "Email is required" });
signups.Add(input);
return Results.Created($"/signups/{signups.Count}", input);
});string.IsNullOrWhiteSpace는 null, "", 공백만으로 이루어진 텍스트에 대해 true입니다. 오류 본문은 클라이언트에 무엇을 수정해야 하는지 알려줍니다.
챌린지
쉬움POST /api/recipes는 이름이 없거나 조리 시간이 없는 레시피를 거부합니다.
Program.cs에서 POST 람다의 맨 위에string.IsNullOrWhiteSpace(input.Name)일 때Results.BadRequest(new { error = "Name is required" })를 반환하도록 합니다.- 다음으로
input.Minutes <= 0일 때Results.BadRequest(new { error = "Minutes must be more than 0" })를 반환하도록 합니다. - 두 검사는 레시피를 만들고 추가하기 전에 수행되므로, 거부된 레시피는 저장되지 않으며 ID도 사용하지 않습니다.
직접 해보기: ‘실행’을 누르고 {"category":"soup","minutes":30}을 /api/recipes에 POST하세요. 상태 코드는 400이고 {"error":"Name is required"}가 반환됩니다. {"name":"Toast","category":"breakfast","minutes":0}을 POST하면 {"error":"Minutes must be more than 0"}가 반환됩니다. 그런 다음 {"name":"Waffles","category":"breakfast","minutes":20}을 POST하면 ID 4와 함께 201이 반환됩니다.
직접 해보기
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) =>
{
var recipe = new Recipe(nextId++, input.Name, input.Category, input.Minutes);
recipes.Add(recipe);
return Results.Created($"/api/recipes/{recipe.Id}", recipe);
});
app.Run();