정적 HTML 페이지
Coddy ASP.NET Core 여정의 Minimal API 섹션에 포함된 레슨. 20개 중 12번째.
웹 앱은 HTML 페이지, CSS, 이미지처럼 변경되지 않는 파일을 자주 전송합니다. 프로젝트에 정적 파일 미들웨어를 추가하면 ASP.NET Core가 프로젝트의 wwwroot 폴더에서 해당 파일을 제공합니다. 미들웨어는 각 요청이 엔드포인트에 도달하기까지 거치는 코드이며, 다음 장에서 직접 작성해 봅니다.
var app = builder.Build();
app.UseStaticFiles();프로젝트에 wwwroot/about.html과 wwwroot/css/site.css가 있으면 GET /about.html과 GET /css/site.css 요청은 해당 파일을 응답으로 반환하며, 확장자에 맞는 Content-Type을 지정합니다. 각각 text/html, text/css입니다. 주소는 wwwroot 자체를 제외한 wwwroot 안의 경로입니다. 존재하지 않는 파일을 요청하면 요청은 엔드포인트로 계속 전달되므로 GET / 요청은 여전히 MapGet("/")에 도달합니다.
챌린지
쉬움API에 홈 페이지가 추가됩니다. wwwroot/index.html이 프로젝트에 새로 추가되었습니다.
Program.cs에서var app = builder.Build();다음 줄에app.UseStaticFiles();를 추가하세요.wwwroot/index.html에서 첫 번째 단락 아래에<p><a href="/api/recipes">All recipes</a></p>를 추가하세요.
직접 해 보세요: 실행을 누르세요. 첫 번째 요청은 GET /index.html입니다. 상태 코드는 200이고, Content-Type: text/html이며, 페이지에 Recipe Box라는 제목이 표시됩니다. Source 탭에 HTML이 표시됩니다. All recipes를 클릭해 GET /api/recipes를 보내세요. GET /을 보내면 여전히 Recipe API is running이 표시됩니다.
직접 해보기
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;
var favoriteIds = new List<int>();
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();
});
var favorites = app.MapGroup("/api/favorites");
favorites.MapGet("/", () => recipes.Where(r => favoriteIds.Contains(r.Id)));
favorites.MapPost("/{id:int}", (int id) =>
{
if (!recipes.Any(r => r.Id == id))
return Results.NotFound(new { error = $"Recipe {id} not found" });
if (!favoriteIds.Contains(id))
favoriteIds.Add(id);
return Results.NoContent();
});
favorites.MapDelete("/{id:int}", (int id) =>
{
favoriteIds.Remove(id);
return Results.NoContent();
});
app.Run();