- Home
- .NET coding challenges
- Using data annotations for Web API model validation
Using data annotations for Web API model validation
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?
Give us your anonymous feedback regarding this page, or any other areas of the website.
Related challenges

Add model binding in an ASP.NET Core Web API
ASP.NET Core Web API model binding coding challenge to add the [FromHeader] attribute in an action.