Menu
CoddyTech

Yêu cầu không hợp lệ

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

Phần nội dung có thể bỏ qua một thuộc tính: {} vẫn được liên kết, và input.Email là null dù bản ghi khai báo kiểu string. Kiểu tham chiếu có thể nhận giá trị null chỉ đưa ra cảnh báo khi biên dịch code, chúng không kiểm tra JSON. Vì vậy, endpoint tự kiểm tra các giá trị và trả lời bằng 400 Bad Request với Results.BadRequest trước khi thay đổi bất cứ thứ gì.

app.MapPost("/signups", (Signup input) =>
{
    if (string.IsNullOrWhiteSpace(input.Email))
        return Results.BadRequest(new { error = "Email is required" });
    signups.Add(input);
    return Results.Created($"/signups/{signups.Count}", input);
});

string.IsNullOrWhiteSpace trả về true với null, với "" và với văn bản chỉ chứa dấu cách. Phần nội dung lỗi cho client biết cần sửa gì.

challenge icon

Thử thách

Dễ

POST /api/recipes từ chối công thức không có tên hoặc không có thời gian nấu.

  1. Trong Program.cs, ở đầu lambda POST, khi string.IsNullOrWhiteSpace(input.Name), trả về Results.BadRequest(new { error = "Name is required" }).
  2. Tiếp theo, khi input.Minutes <= 0, trả về Results.BadRequest(new { error = "Minutes must be more than 0" }).
  3. Cả hai bước kiểm tra đều diễn ra trước khi tạo và thêm công thức, vì vậy công thức bị từ chối sẽ không bao giờ được lưu và không dùng đến id.

Thử nhé: nhấn Chạy và gửi POST {"category":"soup","minutes":30} đến /api/recipes: trạng thái 400 và {"error":"Name is required"}. Gửi POST {"name":"Toast","category":"breakfast","minutes":0}: {"error":"Minutes must be more than 0"}. Sau đó gửi POST {"name":"Waffles","category":"breakfast","minutes":20}: 201 với id 4.

Tự làm thử

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) =>
{
    var recipe = new Recipe(nextId++, input.Name, input.Category, input.Minutes);
    recipes.Add(recipe);
    return Results.Created($"/api/recipes/{recipe.Id}", recipe);
});

app.Run();

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