Add validation attributes to your model properties. These attributes will be used to validate the data that is submitted to your API.
In your controller action, check the ModelState property. This property will contain a list of any validation errors that occurred.
If there are any validation errors, return a 400 Bad Request response. The response should include a JSON object that lists the validation errors.
The following code shows how to handle model validation errors in a .NET Core API:
C#
[ApiController]
[Route("[controller]")]
public class ProductController : ControllerBase {
[HttpPost]
public IActionResult Create([FromBody] Product product) {
// Validate the product data.
if (!ModelState.IsValid) {
return BadRequest(ModelState.GetErrors());
}
// Save the product data.
// ...
return Ok(product);
}
}
In this code, the Create() action method validates the product data before saving it to the database. If the data is invalid, the method returns a 400 Bad Request response.
Here are some additional things to keep in mind about handling model validation errors in a .NET Core API:
You can use the ModelState.IsValid property to check if the model data is valid.
You can use the ModelState.GetErrors() method to get a list of the validation errors.
You can return a 400 Bad Request response to indicate that the request was invalid.
You can include a JSON object in the response that lists the validation errors.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To handle model validation errors in a .NET Core API, you can use the following steps:
ModelStateproperty. This property will contain a list of any validation errors that occurred.The following code shows how to handle model validation errors in a .NET Core API:
C#
In this code, the
Create()action method validates the product data before saving it to the database. If the data is invalid, the method returns a 400 Bad Request response.Here are some additional things to keep in mind about handling model validation errors in a .NET Core API:
ModelState.IsValidproperty to check if the model data is valid.ModelState.GetErrors()method to get a list of the validation errors.