Data annotations are a set of attributes that can be applied to classes and properties in .NET to specify metadata about the data. They are commonly used for validation, formatting, and defining relationships between data models. In ASP.NET Web API, data annotations play a crucial role in validating incoming data, ensuring that it meets specific criteria before being processed by the application.
Key Features of Data Annotations
- Validation: Data annotations can enforce validation rules on model properties, such as required fields, string length, range of values, and more.
- Metadata: They provide additional information about the data, which can be used for documentation or UI generation.
- Serialization: Data annotations can influence how data is serialized and deserialized, such as formatting dates or controlling JSON property names.
- Integration: They work seamlessly with model binding and validation in ASP.NET MVC and Web API, making it easy to validate incoming requests.
Commonly Used Data Annotations
Here are some commonly used data annotations in ASP.NET Web API:
[Required]
: Specifies that a property must have a value.[StringLength(maximumLength)]
: Limits the length of a string property.[Range(minimum, maximum)]
: Specifies the range of valid values for a numeric property.[EmailAddress]
: Validates that a property contains a valid email address.[RegularExpression(pattern)]
: Validates that a property matches a specified regular expression.
Creating a Model with Data Annotations
Below is an example of a model class that uses data annotations for validation:
using System.ComponentModel.DataAnnotations;
public class Product
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Product name is required.")]
[StringLength(100, ErrorMessage = "Product name cannot exceed 100 characters.")]
public string Name { get; set; }
[Range(0.01, 10000.00, ErrorMessage = "Price must be between 0.01 and 10,000.00.")]
public decimal Price { get; set; }
[EmailAddress(ErrorMessage = "Invalid email address.")]
public string SupplierEmail { get; set; }
}
Explanation of the Model Code
In the Product
model:
- The
[Key]
attribute indicates that theId
property is the primary key for the model. - The
[Required]
attribute ensures that theName
property must be provided when creating or updating a product. - The
[StringLength(100)]
attribute limits the length of theName
property to a maximum of 100 characters. - The
[Range(0.01, 10000.00)]
attribute ensures that thePrice
property must be between 0.01 and 10,000.00. - The
[EmailAddress]
attribute validates that theSupplierEmail
property contains a valid email address.
Using Data Annotations in Controllers
When you receive data in your Web API controllers, you can validate the model using the ModelState.IsValid
property. If the model is invalid, you can return a bad request response with the validation errors. Below is an example of how to validate a model in a controller:
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
public class ProductsController : ApiController
{
private static List<Product> products = new List<Product>();
// POST api/products
public IHttpActionResult Post([FromBody] Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // Return validation errors
}
products.Add(product); // Add the new product
return CreatedAtRoute("DefaultApi", new { id = product.Id }, product); // Return 201
}
}
Conclusion
Data annotations are a powerful feature in ASP.NET Web API that allow developers to enforce validation rules and provide metadata for model properties. By using data annotations, you can ensure that the data received from clients is valid and meets the required criteria, enhancing the reliability and security of your web application.