Published: Monday 9 October 2023
Data annotations can be used in ASP.NET Core to validate a model through a Web API endpoint.
You can learn more about data annotations by watching our video:
We have this CustomerModel
class which contains properties for the first name and surname.
public class CustomerModel
{
public string? FirstName { get; init; }
public string? Surname { get; init; }
}
In-addition, we have this CustomerController
class which has a Web API endpoint that tries to create a customer record.
[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
[HttpPost]
public IActionResult Create(CustomerModel customerModel)
{
return Ok(customerModel);
}
}
When we run the Create
Web API endpoint, we want to ensure that both theĀ FirstName
and Surname
properties in the CustomerModel
have a value set. How can we do that with theĀ Required
attribute?