Lesson 34 of 40 Web API Intermediate 40 min

Validation in Web API

Learn how validation works in ASP.NET Core Web API and how to ensure incoming data is correct, complete, and safe before processing it in your application.

Part 1: What Is Validation?

Validation is the process of checking whether incoming data meets certain rules or requirements.

It ensures that:

Without validation, your application may behave incorrectly or become vulnerable to attacks.

Part 2: Why Validation Is Important

Validation is critical in Web API because APIs often receive data from external sources.

Part 3: Data Annotations

ASP.NET Core uses data annotations to define validation rules on models.

public class Student
{
  [Required]
  public string Name { get; set; }

  [Range(1, 100)]
  public int Age { get; set; }
}

These attributes define validation rules automatically.

Part 4: Checking Model State

After model binding, ASP.NET Core checks whether the data is valid.

[HttpPost]
public IActionResult Create(Student student)
{
  if (!ModelState.IsValid)
  {
    return BadRequest(ModelState);
  }

  return Ok(student);
}

If validation fails, the API returns an error response.

Part 5: Automatic Validation with ApiController

When using the [ApiController] attribute, ASP.NET Core automatically validates incoming data and returns errors if the model is invalid.

This reduces the need for manual validation checks.

Part 6: Common Validation Attributes

Attribute Purpose
[Required] Ensures a value is provided
[StringLength] Limits string length
[Range] Restricts numeric values
[EmailAddress] Validates email format

Part 7: Validation in the Student Project

In your Student API, validation ensures data integrity:

This improves both user experience and system reliability.

Part 8: Best Practices

Proper validation ensures your application remains secure and reliable.

Summary

Validation is a key part of building robust ASP.NET Core Web APIs. By using data annotations and model validation, you can ensure that only valid data is processed, improving both security and reliability.

VISUAL STUDIO 2026 MADE EASY
Recommended Book

VISUAL STUDIO 2026 MADE EASY

Build real applications with C#, VB.NET, Python, JavaScript, C++, and .NET 10. A practical companion for mastering Visual Studio 2026 step by step.