Menu
CoddyTech

쿼리 문자열

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

쿼리 문자열은 주소에서 ? 뒤에 오는 부분입니다. /books?author=austen&page=2처럼 이름과 값의 쌍이 &로 연결됩니다. 쿼리 문자열은 경로를 선택하지 않고 요청에 옵션을 추가합니다. 경로에 이름이 없는 람다 매개변수는 쿼리 문자열에서 읽습니다.

app.MapGet("/books", (string? author, int page = 1) =>
    $"Books by {author ?? "anyone"}, page {page}");

GET /books?author=austen은 Books by austen, page 1을 반환합니다. string?처럼 nullable이거나 기본값이 있는 매개변수는 선택 사항입니다. 일반 string은 필수입니다. 이 값이 없으면 ASP.NET Core는 400 Bad Request를 반환하고 람다는 실행되지 않습니다.

challenge icon

챌린지

쉬움

GET /api/recipes에 필터링 기능을 추가합니다. ?category=soup는 수프만 남깁니다.

  1. Program.cs에서 GET /api/recipes 람다에 string? category 매개변수를 추가하세요.
  2. Category가 category와 같은 레시피를 반환하세요. category가 null이면 모든 레시피를 반환하세요: recipes.Where(r => category is null || r.Category == category).

직접 해 보세요: ‘실행’을 누르세요. GET /api/recipes?category=soup는 수프 두 개, id 1과 3을 반환합니다. GET /api/recipes를 보내세요: 레시피 세 개 모두. GET /api/recipes?category=dessert를 보내세요: 빈 목록, [].

직접 해보기

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", () => recipes);
app.MapGet("/api/recipes/{id:int}", (int id) => recipes.FirstOrDefault(r => r.Id == id));

app.Run();

Minimal API의 모든 레슨