Menu
CoddyTech

初めてのミドルウェア

CoddyのASP.NET Coreジャーニー「Minimal API」セクションの一部。レッスン 13/20。

ミドルウェアは、エンドポイントが応答する前に、アプリが追加した順序で、すべてのリクエストが通過するコードです。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

チャレンジ

簡単

すべてのレスポンスで、ヘッダー X-Api-Version: 1 に、どのバージョンの API が応答したかが示されます。

  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のすべてのレッスン