Menu
CoddyTech

요청 조기 종료하기

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

next()를 호출하지 않는 미들웨어는 그 지점에서 요청을 끝내고 직접 응답합니다. 그 아래에 있는 미들웨어, 정적 파일 및 엔드포인트는 실행되지 않습니다.

app.Use(async (context, next) =>
{
    if (context.Request.Path.StartsWithSegments("/admin"))
    {
        context.Response.StatusCode = 403;
        await context.Response.WriteAsync("Forbidden");
        return;
    }
    await next();
});

StartsWithSegments("/admin")은 /admin과 /admin/users에서는 true이고, /administrator에서는 그렇지 않습니다. 클라이언트를 다른 주소로 보내려면 context.Response.Redirect(url, permanent: true)가 Location 헤더에 주소를 담아 301 영구 이동 응답을 보내며, 그러면 브라우저가 해당 주소를 요청합니다. permanent: true가 없으면 지금만 이동하는 302 찾음 응답을 보냅니다.

challenge icon

챌린지

쉬움

API는 /api 없이 /recipes에서 제공되었습니다. 이전 링크는 새 주소로 연결됩니다.

  1. Program.cs에서 X-Api-Version 미들웨어 아래, app.UseStaticFiles(); 위에 app.Use 미들웨어를 하나 더 추가하세요.
  2. context.Request.Path.StartsWithSegments("/recipes")인 경우 context.Response.Redirect("/api" + context.Request.Path + context.Request.QueryString, permanent: true);를 호출하고, next()를 호출하지 말고 return하세요.
  3. 그렇지 않으면 await next();를 호출하세요.

시도해 보세요: ‘실행’을 누르세요. 첫 번째 요청은 GET /recipes/2입니다. 상태 코드는 301이고, Headers 탭에는 Location: /api/recipes/2와 X-Api-Version: 1이 표시됩니다. GET /recipes?category=soup를 보내세요. Location: /api/recipes?category=soup가 표시됩니다. GET /api/recipes/2를 보내세요. 리디렉션되지 않고 200이 반환됩니다.

직접 해보기

using Microsoft.AspNetCore.Http.HttpResults;

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

app.Use(async (context, next) =>
{
    context.Response.Headers["X-Api-Version"] = "1";
    await next();
});

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();

Minimal API의 모든 레슨