Junior — Middle
What approaches are used to verify data correctness in ASP.NET Core?
sobes.tech AI
Answer from AI
In ASP.NET Core, validation attributes are often used to check the correctness of data, which are applied to data models. For example, attributes like [Required], [StringLength], [Range], and others from the System.ComponentModel.DataAnnotations namespace allow you to specify validation rules directly in the model.
Controllers can check the validity of the model through the ModelState.IsValid property. If the data does not pass validation, an error can be returned to the client.
Example:
public class UserModel
{
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[Range(18, 99, ErrorMessage = "Age must be between 18 and 99")]
public int Age { get; set; }
}
[HttpPost]
public IActionResult CreateUser(UserModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// User saving logic
return Ok();
}
You can also create custom validation attributes or use FluentValidation for more complex scenarios.