Menu
CoddyTech

Middleware đầu tiên của bạn

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

Middleware là code mà mọi request đều đi qua, theo thứ tự ứng dụng thêm chúng, trước khi một endpoint phản hồi. app.Use thêm một middleware. Middleware nhận HttpContext, chứa request và response, cùng với next, thành phần chạy phần còn lại của pipeline.

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

Code trước await next() chạy trên đường đi vào, code sau nó chạy trên đường quay ra. Response gửi header trước body, vì vậy hãy đặt header trước next(): một khi endpoint đã ghi body, bạn không thể thay đổi chúng nữa. Middleware chỉ thấy những request đi đến nó, còn app.UseStaticFiles() tự xử lý request tệp, nên middleware được thêm bên dưới nó sẽ không bao giờ thấy /index.html.

challenge icon

Thử thách

Dễ

Mỗi phản hồi cho biết phiên bản API đã trả lời yêu cầu đó trong tiêu đề X-Api-Version: 1.

  1. Trong Program.cs, giữa var app = builder.Build(); và app.UseStaticFiles();, thêm middleware bằng app.Use(async (context, next) => { ... });.
  2. Lệnh này đặt context.Response.Headers["X-Api-Version"] = "1";, sau đó gọi await next();.

Thử nhé: nhấn Chạy. GET /api/recipes vẫn trả lời như trước, và thẻ Headers hiển thị X-Api-Version: 1. Gửi GET /index.html: tiêu đề này cũng xuất hiện. Gửi GET /nothing: trạng thái 404, kèm tiêu đề này.

Tự làm thử

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