Model validation is a crucial aspect of building any web API. It ensures that the data entered by the user is valid, consistent, and conforms to the expected data types. .NET Web API provides several ways to perform model validation, including Data Annotations, Fluent Validation, and custom validation.
In this blog, we will focus on using Data Annotations for model validation in .NET Web API.
What are Data Annotations?
Data Annotations are a set of attributes that can be applied to properties of a class to specify validation rules. These attributes provide a declarative way of defining validation rules without writing custom validation code.
using System.ComponentModel.DataAnnotations;
public class Person
{
[Required]
[StringLength(50)]
public string Name { get; set; }
[Range(18, 100)]
public int Age { get; set; }
[RegularExpression(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$")]
public string Email { get; set; }
}
In this above example, we have defined a Person class with three properties: Name, Age, and Email. We have applied Data Annotation attributes to each property to specify validation rules.
The Required attribute is used to indicate that the Name property is required, while the StringLength attribute specifies that the maximum length of the Name property is 50 characters.
The Range attribute is used to specify that the Age property should be between 18 and 100. The RegularExpression attribute is used to specify a regular expression pattern that the Email property should match.
To enable model validation in .NET Web API, we need to add the [ApiController]
attribute to the controller and the [FromBody]
attribute to the action method parameter.
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
[HttpPost]
public IActionResult CreatePerson([FromBody] Person person)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Code to create a person
return Ok(person);
}
}
In this example, we have added the [ApiController]
attribute to the PersonController class to enable automatic model validation. We have also added the [FromBody]
attribute to the CreatePerson action method parameter to indicate that the Person object will be provided in the request body.
The ModelState.IsValid
property is used to check if the Person object passes all the validation rules defined in the model. If the object fails validation, a BadRequest
response is returned along with the validation errors. If the model is valid, the code to create the person is executed, and the person object is returned in the response with an HTTP status code of 200 (OK).
public class Person
{
[Required(ErrorMessage = "Person Name is required.")]
[StringLength(50, ErrorMessage = "Name cannot be longer than 50 characters.")]
public string Name { get; set; }
[Required(ErrorMessage = "Person Email is required.")]
[EmailAddress(ErrorMessage = "Invalid Email Address.")]
public string Email { get; set; }
[Range(18, 60, ErrorMessage = "Age should be between 18 and 60.")]
public int Age { get; set; }
}
We can also give custom error messages as shown in above example.
Benefits of using Data Annotations for model validation in .NET Web API:
- Data Annotations provide a declarative way of defining validation rules without writing custom validation code.
- Data Annotations can be easily applied to properties of a class, making it easier to define validation rules.
- Data Annotations provide a consistent way of defining validation rules across the application.
No Comment! Be the first one.