Menu
CoddyTech

ルートグループ

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

同じリソースのエンドポイントは、ルートの先頭部分を共有します。app.MapGroup(prefix) はルートグループを作成します。このグループにマッピングされた各エンドポイントには、それぞれのパターンの前にプレフィックスが付加されます。

var orders = app.MapGroup("/api/orders");
orders.MapGet("/", () => orderList);
orders.MapGet("/{id:int}", (int id) => orderList.FirstOrDefault(o => o.Id == id));
orders.MapDelete("/{id:int}", (int id) => orderList.RemoveAll(o => o.Id == id));

ルートは /api/orders/、/api/orders/{id:int}、そして同じパターンに対する DELETE です。末尾のスラッシュがどのルートにマッチするかを変えないため、GET /api/orders は /api/orders/ にマッチします。プレフィックスは一度だけ記述するので、名前を変更する場合も変更箇所は1行だけです。また、グループを使って、ログインを必須にするなど、すべてのエンドポイントに設定を適用できます。グループ内でプレフィックスを再度記述すると、重複します。/api/orders/api/orders/{id:int}。

challenge icon

チャレンジ

簡単

学習者はお気に入りのレシピを登録できます。3つのお気に入りエンドポイントは、1つのグループを共有します。

  1. Program.csで、nextIdの下にvar favoriteIds = new List<int>();を追加します。
  2. app.Run()の上に、グループを作成します:var favorites = app.MapGroup("/api/favorites");。
  3. このグループにGET "/"をマッピングします:IdがfavoriteIdsに含まれるレシピを、recipesの順序で返します。
  4. POST "/{id:int}"をマッピングします:そのIDのレシピがない場合は、Results.NotFound(new { error = $"Recipe {id} not found" })を返します。そうでなければ、favoriteIdsにすでに含まれている場合を除いてIDを追加し、Results.NoContent()を返します。
  5. DELETE "/{id:int}"をマッピングします:favoriteIdsからIDを削除し、Results.NoContent()を返します。

試してみましょう:「実行」を押します:GET /api/favoritesは[]を返します。空の本文でPOST /api/favorites/2を送信します:ステータス204。GET /api/favoritesを送信します:Pancakesのレシピを含むリストが返されます。POST /api/favorites/99は404を返し、DELETE /api/favorites/2を送信すると、リストは再び空になります。

自分で試してみよう

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;

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

app.Run();
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Minimal APIのすべてのレッスン