Menu
CoddyTech

첫 번째 미들웨어

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

미들웨어는 앱이 추가한 순서대로 모든 요청이 통과하는 코드이며, 엔드포인트가 응답하기 전에 실행됩니다. app.Use로 미들웨어를 추가합니다. 미들웨어는 요청과 응답을 담고 있는 HttpContext와 나머지 파이프라인을 실행하는 next를 받습니다.

app.Use(async (context, next) =>
{
    context.Response.Headers["Cache-Control"] = "no-store";
    await next();
});

await next() 이전의 코드는 요청이 들어올 때 실행되고, 이후의 코드는 응답이 나갈 때 실행됩니다. 응답은 본문을 보내기 전에 헤더를 보내므로, next() 이전에 헤더를 설정하세요. 엔드포인트가 본문을 작성한 뒤에는 헤더를 더 이상 변경할 수 없습니다. 미들웨어는 자신에게 도달하는 요청만 확인하며, app.UseStaticFiles()는 파일 요청에 직접 응답하므로 그 아래에 추가된 미들웨어는 /index.html을 확인하지 못합니다.

challenge icon

챌린지

쉬움

모든 응답에는 응답을 보낸 API의 버전이 헤더 X-Api-Version: 1에 표시됩니다.

  1. Program.cs에서 var app = builder.Build();와 app.UseStaticFiles(); 사이에 app.Use(async (context, next) => { ... });를 사용해 미들웨어를 추가하세요.
  2. context.Response.Headers["X-Api-Version"] = "1";을 설정한 다음 await next();를 호출합니다.

실행해 보세요: ‘실행’을 누르세요. GET /api/recipes는 이전과 같이 응답하고, Headers 탭에 X-Api-Version: 1이 표시됩니다. GET /index.html을 보내세요. 여기에도 헤더가 있습니다. GET /nothing을 보내세요. 상태 코드는 404이고 헤더가 포함됩니다.

직접 해보기

using Microsoft.AspNetCore.Http.HttpResults;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseStaticFiles();

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();
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Minimal API의 모든 레슨