Thông thường trong asp.net core/mvc ta hay sử dụng các attribute để check điều kiện validate cho model, ví dụ như
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class User { [Required] [StringLength(250)] public string DisplayName { get; set; } [Required] public string Email { get; set; } public string Phone { get; set; } public string Password { get; set; } } |
Trong action method kiểm tra model hợp lệ hay không bằng cách sử dụng ModelState
1 2 3 4 5 6 7 8 9 10 11 |
[HttpPut] [Route("update")] public async Task<IActionResult> Update([FromBody]User model) { if (!ModelState.IsValid) { throw new Exception("Dữ liệu đầu vào không hợp lệ"); } // your code here... } |
Cách này hoạt động tốt tuy nhiên hơi nông dân vì phải check điều kiện ở nhiều Action method, nhiều controller khác nhau. Dẫn đến code bị lặp lại nhiều lần, trông không đẹp & khó bảo trì. Để khắc phục tình trạng này thì bây giờ chúng ta sẽ sử dụng Action filter để validate như sau
Bước 1 : Tạo 1 class cho action filter, dùng để validate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class ValidationActionFilter : IActionFilter { /// <inheritdoc /> public void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.ModelState.IsValid) { // trả về một json filterContext.Result = new JsonResult(new { success = false, message = "Dữ liệu đầu vào không hợp lệ" }); // Bạn có thể trả về json như trên hoặc trả về 1 mã lỗi cụ thể, ví dụ BadRequest // filterContext.Result = new BadRequestObjectResult(filterContext.ModelState); } } /// <inheritdoc /> |