Data validation is a crucial aspect of any web application, ensuring that the data received from clients meets specific criteria before being processed. In ASP.NET Web API, you can implement data validation using data annotations, model validation, and custom validation logic. This guide will explain how to implement data validation in ASP.NET Web API with sample code.

1. Using Data Annotations

Data annotations are attributes that you can apply to model properties to enforce validation rules. Commonly used data annotations include [Required], [StringLength], [Range], and [EmailAddress]. Below is an example of a model with 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; }
}

Explanation of Data Annotations

In the Product model:

  • The [Required] attribute ensures that the Name property must be provided when creating or updating a product.
  • The [StringLength(100)] attribute limits the length of the Name property to a maximum of 100 characters.
  • The [Range(0.01, 10000.00)] attribute ensures that the Price property must be between 0.01 and 10,000.00.

2. Validating Models 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
}
}

Explanation of the Controller Code

In the ProductsController example:

  • The Post() method handles POST requests to api/products. It checks if the incoming Product model is valid using ModelState.IsValid.
  • If the model is invalid, it returns a 400 Bad Request response along with the validation errors contained in ModelState.
  • If the model is valid, it adds the product to the list and returns a 201 Created response.

3. Custom Validation Attributes

In addition to built-in data annotations, you can create custom validation attributes to implement more complex validation logic. Below is an example of a custom validation attribute:

        
using System;
using System.ComponentModel.DataAnnotations;

public class PriceMustBePositiveAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value is decimal price && price <= 0)
{
return new ValidationResult("Price must be a positive value.");
}
return ValidationResult.Success;
}
}

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; }

[PriceMustBePositive(ErrorMessage = "Price must be a positive value.")]
public decimal Price { get; set; }
}

Explanation of Custom Validation

In the custom validation example:

  • The PriceMustBePositiveAttribute class inherits from ValidationAttribute and overrides the IsValid method to implement custom validation logic.
  • If the Price property is less than or equal to zero, it returns a validation error message.
  • This custom attribute can be applied to the Price property in the Product model to enforce the rule that the price must be positive.

Conclusion

Implementing data validation in ASP.NET Web API is essential for ensuring data integrity and providing a better user experience. By using data annotations, validating models in controllers, and creating custom validation attributes, you can effectively manage and enforce validation rules in your application. This approach not only helps in maintaining clean and reliable data but also enhances the overall security of your API by preventing invalid data from being processed.