Menu
CoddyTech

Nhóm route

Thuộc phần Minimal API trong hành trình ASP.NET Core của Coddy. Bài học 11 trên 20.

Các endpoint của cùng một tài nguyên có chung phần đầu của đường dẫn. app.MapGroup(prefix) tạo một nhóm đường dẫn: mỗi endpoint được ánh xạ vào nhóm sẽ có tiền tố đứng trước mẫu đường dẫn của riêng nó.

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

Các đường dẫn là /api/orders/, /api/orders/{id:int} và phương thức DELETE trên cùng mẫu đường dẫn. GET /api/orders khớp với /api/orders/, vì dấu gạch chéo ở cuối không làm thay đổi đường dẫn được khớp. Tiền tố chỉ cần viết một lần, nên khi đổi tên, bạn chỉ cần sửa một dòng; nhóm cũng có thể áp dụng các cài đặt cho mọi endpoint trong nhóm, chẳng hạn như yêu cầu đăng nhập. Viết lại tiền tố bên trong nhóm sẽ khiến tiền tố bị lặp đôi: /api/orders/api/orders/{id:int}.

challenge icon

Thử thách

Dễ

Người học có thể lưu các công thức nấu ăn yêu thích. Ba endpoint yêu thích dùng chung một nhóm.

  1. Trong Program.cs, bên dưới nextId, thêm var favoriteIds = new List<int>();.
  2. Phía trên app.Run(), tạo nhóm: var favorites = app.MapGroup("/api/favorites");.
  3. Trên nhóm đó, ánh xạ GET "/": endpoint này trả về các công thức có Id nằm trong favoriteIds, theo thứ tự trong recipes.
  4. Ánh xạ POST "/{id:int}": nếu không có công thức nào có id đó, hãy trả về Results.NotFound(new { error = $"Recipe {id} not found" }). Nếu có, hãy thêm id đó nếu favoriteIds chưa chứa id này, rồi trả về Results.NoContent().
  5. Ánh xạ DELETE "/{id:int}": xóa id đó khỏi favoriteIds rồi trả về Results.NoContent().

Thử nhé: nhấn Chạy: GET /api/favorites trả về []. Gửi POST /api/favorites/2 với phần thân rỗng: mã trạng thái 204. Gửi GET /api/favorites: một danh sách có công thức Pancakes. POST /api/favorites/99 trả về 404, còn DELETE /api/favorites/2 làm danh sách trống trở lại.

Tự làm thử

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 iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Minimal API