Thuộc tính xác thực
Thuộc phần REST API trong hành trình ASP.NET Core của Coddy. Bài học 7 trên 20.
Viết từng quy tắc bằng if sẽ khiến code dài dòng. Chú thích dữ liệu (data annotations) đặt các quy tắc dưới dạng thuộc tính trên kiểu dữ liệu, từ System.ComponentModel.DataAnnotations, còn Validator kiểm tra một đối tượng dựa trên các quy tắc đó.
record SignupInput(
[property: Required, EmailAddress] string Email,
[property: Range(13, 120)] int Age);
var results = new List<ValidationResult>();
Validator.TryValidateObject(input, new ValidationContext(input), results,
validateAllProperties: true);Trong một bản ghi vị trí, property: đặt thuộc tính lên thuộc tính dữ liệu, là nơi Validator tìm kiếm. Nếu không có validateAllProperties: true, nó chỉ kiểm tra [Required]. Mỗi quy tắc bị vi phạm sẽ thêm một ValidationResult chứa tên thuộc tính và thông báo. .NET 10 cũng có builder.Services.AddValidation(), giúp kiểm tra các tham số của endpoint, nhưng với kiểu dữ liệu do bạn tự tạo, tính năng này cần một trình tạo mã (source generator). Trình chạy ở đây không chạy trình tạo mã, nên bạn tự gọi Validator.
Thử thách
Trung bìnhChuyển các quy tắc về tiêu đề vào TaskInput và thêm một quy tắc mới: tiêu đề có tối đa 80 ký tự.
- Bạn có một tệp mới,
Validation.cs. Phương thứcErrorschuyển kết quả thành từ điển màResults.ValidationProblemnhận. Tại vị trí chú thích, hãy gọiValidator.TryValidateObjecttrênmodelvớinew ValidationContext(model),resultsvàvalidateAllProperties: true. - Ở đầu
Program.cs, thêmusing System.ComponentModel.DataAnnotations;và gắn hai thuộc tính này choTitlecủaTaskInput:[property: Required(ErrorMessage = "Title is required."), StringLength(80)]. - Trong POST và PUT, thay phần kiểm tra
IsNullOrWhiteSpacebằngvar errors = Validation.Errors(input);và trả vềResults.ValidationProblem(errors)khi giá trị không phảinull.
Giờ đây, tiêu đề gồm 81 ký tự sẽ trả về mã 400 cùng nội dung:
"errors": { "title": ["The field Title must be a string with a maximum length of 80."] }Thử nhé: nhấn Run rồi gửi POST với phần thân có tiêu đề gồm 81 chữ cái đến /api/tasks: nhận mã 400 và lỗi ở trên. Gửi POST với { "title": "" }: nhận mã 400 cùng lỗi Title is required. như trước. Gửi POST với { "title": "Order new chairs" }: nhận mã 201.
Tự làm thử
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var tasks = new List<TaskItem>
{
new(1, "Write the project brief", false),
new(2, "Book the meeting room", true),
new(3, "Send the invoice", false),
};
var nextId = 4;
app.MapGet("/api/tasks", () => tasks);
app.MapGet("/api/tasks/{id:int}", (int id) =>
{
var task = tasks.Find(t => t.Id == id);
return task is null ? Results.NotFound() : Results.Ok(task);
});
app.MapPost("/api/tasks", (TaskInput input) =>
{
if (string.IsNullOrWhiteSpace(input.Title))
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["title"] = ["Title is required."],
});
}
var task = new TaskItem(nextId++, input.Title, input.Done);
tasks.Add(task);
return Results.Created($"/api/tasks/{task.Id}", task);
});
app.MapPut("/api/tasks/{id:int}", (int id, TaskInput input) =>
{
if (string.IsNullOrWhiteSpace(input.Title))
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["title"] = ["Title is required."],
});
}
var index = tasks.FindIndex(t => t.Id == id);
if (index == -1) return Results.NotFound();
tasks[index] = new TaskItem(id, input.Title, input.Done);
return Results.Ok(tasks[index]);
});
app.MapPatch("/api/tasks/{id:int}", (int id, TaskPatch patch) =>
{
var index = tasks.FindIndex(t => t.Id == id);
if (index == -1) return Results.NotFound();
var task = tasks[index];
tasks[index] = task with
{
Title = patch.Title ?? task.Title,
Done = patch.Done ?? task.Done,
};
return Results.Ok(tasks[index]);
});
app.MapDelete("/api/tasks/{id:int}", (int id) =>
{
var removed = tasks.RemoveAll(t => t.Id == id);
return removed == 0 ? Results.NotFound() : Results.NoContent();
});
app.Run();
record TaskItem(int Id, string Title, bool Done);
record TaskInput(string Title, bool Done);
record TaskPatch(string? Title, bool? Done);
Tất cả bài học trong REST API
1Tài nguyên và động từ
Tài nguyên và URLTạo mới bằng POST4Dự án: Mức độ ưu tiên
Mức độ ưu tiên của tác vụ