Mid REST API

How would you handle validation errors in a REST API?

  • Use model validation with data annotations.
  • Return 400 Bad Request with a list of validation errors.

Example:

public class UserModel

[Required(ErrorMessage = "Email is required")]

[EmailAddress(ErrorMessage = "Invalid email format")]

public string Email { get; set; }

[Required]

[MinLength(6, ErrorMessage = "Password must be at least 6

characters")]

public string Password { get; set; }

// Controller action

[HttpPost("register")]

public IActionResult Register([FromBody] UserModel model)

if (!ModelState.IsValid)

var errors = ModelState.Values.SelectMany(v =>

v.Errors).Select(e => e.ErrorMessage);

return BadRequest(new { status = 400, error = "Validation

Failed", details = errors });

return Ok("User registered successfully");

More from ASP.NET Core Web API Tutorial

All questions for this course