라우트 그룹
Coddy ASP.NET Core 여정의 Minimal API 섹션에 포함된 레슨. 20개 중 11번째.
하나의 리소스에 속한 엔드포인트는 경로의 시작 부분을 공유합니다. app.MapGroup(prefix)는 경로 그룹을 만듭니다. 그룹에 매핑된 모든 엔드포인트의 패턴 앞에 접두사가 붙습니다.
var orders = app.MapGroup("/api/orders");
orders.MapGet("/", () => orderList);
orders.MapGet("/{id:int}", (int id) => orderList.FirstOrDefault(o => o.Id == id));
orders.MapDelete("/{id:int}", (int id) => orderList.RemoveAll(o => o.Id == id));경로는 /api/orders/, /api/orders/{id:int}이며, 같은 패턴에 DELETE도 적용됩니다. 끝에 슬래시가 있어도 일치하는 경로는 바뀌지 않으므로 GET /api/orders는 /api/orders/와 일치합니다. 접두사는 한 번만 작성하므로 이름을 바꾸려면 한 줄만 수정하면 됩니다. 또한 그룹에서 로그인 필요 여부와 같은 설정을 모든 엔드포인트에 적용할 수 있습니다. 그룹 안에 접두사를 다시 작성하면 접두사가 중복됩니다. /api/orders/api/orders/{id:int}.
챌린지
쉬움학습자는 좋아하는 레시피를 저장할 수 있습니다. 즐겨찾기 엔드포인트 세 개는 하나의 그룹을 공유합니다.
Program.cs에서nextId아래에var favoriteIds = new List<int>();를 추가하세요.app.Run()위에 그룹을 만드세요.var favorites = app.MapGroup("/api/favorites");.- 그룹에 GET
"/"을 매핑하세요.favoriteIds에Id가 포함된 레시피를recipes의 순서대로 반환합니다. - POST
"/{id:int}"를 매핑하세요. 해당 id의 레시피가 없으면Results.NotFound(new { error = $"Recipe {id} not found" })를 반환하세요. 그렇지 않으면favoriteIds에 이미 id가 들어 있지 않은 경우 id를 추가하고Results.NoContent()를 반환하세요. - DELETE
"/{id:int}"를 매핑하세요.favoriteIds에서 id를 제거하고Results.NoContent()를 반환하세요.
직접 해보기: 실행을 누르세요. GET /api/favorites는 []를 반환합니다. 빈 본문으로 POST /api/favorites/2를 보내세요. 상태 코드는 204입니다. GET /api/favorites를 보내면 Pancakes 레시피가 포함된 목록이 반환됩니다. POST /api/favorites/99는 404를 반환하고, DELETE /api/favorites/2를 보내면 목록이 다시 비게 됩니다.
직접 해보기
using Microsoft.AspNetCore.Http.HttpResults;
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.MapPut("/api/recipes/{id:int}", (int id, NewRecipe input) =>
{
var index = recipes.FindIndex(r => r.Id == id);
if (index == -1)
return Results.NotFound(new { error = $"Recipe {id} not found" });
var recipe = new Recipe(id, input.Name, input.Category, input.Minutes);
recipes[index] = recipe;
return Results.Ok(recipe);
});
app.MapDelete("/api/recipes/{id:int}", Results<NoContent, NotFound> (int id) =>
{
var removed = recipes.RemoveAll(r => r.Id == id);
return removed > 0 ? TypedResults.NoContent() : TypedResults.NotFound();
});
app.Run();
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.