LESSON 5 OF 18

5. Model Validation and Consistent Request Validation

Validate Product, Category, and Customer requests with DataAnnotations, custom rules, uniqueness checks, and consistent ValidationProblemDetails responses.

55 dk 106

Introduction

The fact that a request can be parsed as JSON does not mean that it is valid. A negative price, an empty name, or an attempt to create a second product with the same SKU is invalid from the API’s perspective. Validation should therefore be treated as a fundamental part of the API contract, not as a collection of scattered if statements inside controllers.

In this lesson, we will validate Product, Category, and Customer request models. We will define required fields, length limits, numeric ranges, email formats, and date rules with DataAnnotations. We will use IValidatableObject and a custom ValidationAttribute for rules involving multiple fields or reusable formats. Finally, we will perform database-backed uniqueness checks in the service layer and return all failures as consistent 400 Bad Request responses using ValidationProblemDetails.

1. Separate validation responsibilities

In a professional API, it is useful to group validation rules into three categories:

  • Shape and basic value validation: Is the field required, is its length valid, is a number within range, and is an email correctly formatted?
  • Cross-field validation: Can a discounted product have a price of zero, or can a customer’s birth date be in the future?
  • Persistence and business-rule validation: Does the SKU, category name, or customer email already exist?

The first two groups can be declared on request DTOs. Rules that require database or external-service access should not be placed directly inside validation attributes. Such attributes are normally synchronous, database access becomes hidden, and testing becomes more difficult. These rules should be checked in the service layer and added to ModelState when they fail.

2. Define request DTOs

Instead of binding entities directly, create DTOs that explicitly describe the fields a client is allowed to submit.

using System.ComponentModel.DataAnnotations; public sealed class CreateProductRequest : IValidatableObject {    [Required(ErrorMessage = "Product name is required.")]    [StringLength(120, MinimumLength = 2,        ErrorMessage = "Product name must be between 2 and 120 characters.")]    public string Name { get; init; } = string.Empty;    [Required(ErrorMessage = "SKU is required.")]    [StringLength(40, MinimumLength = 3,        ErrorMessage = "SKU must be between 3 and 40 characters.")]    [RegularExpression("^[A-Za-z0-9-]+$",        ErrorMessage = "SKU can contain only letters, numbers, and hyphens.")]    public string Sku { get; init; } = string.Empty;    [Range(typeof(decimal), "0.01", "1000000",        ErrorMessage = "Price must be between 0.01 and 1000000.")]    public decimal Price { get; init; }    [Range(0, 100, ErrorMessage = "Discount percentage must be between 0 and 100.")]    public decimal DiscountPercentage { get; init; }    [Required(ErrorMessage = "CategoryId is required.")]    public int? CategoryId { get; init; }    public IEnumerable Validate(ValidationContext validationContext)    {        if (DiscountPercentage > 0 && Price <= 0)        {            yield return new ValidationResult(                "A discounted product must have a positive price.",                new[] { nameof(Price), nameof(DiscountPercentage) });        }    } }

Attributes such as [Required], [StringLength], [Range], and [RegularExpression] are evaluated automatically after model binding. Using int? is important: with a non-nullable int, a missing value and an explicitly submitted zero can be difficult to distinguish. Since the category identifier is required, declaring it as int? and applying [Required] makes the contract clearer.

3. Validate Category and Customer requests

Apply the same approach to the other resources.

public sealed class CreateCategoryRequest : IValidatableObject {    [Required(ErrorMessage = "Category name is required.")]    [StringLength(80, MinimumLength = 2,        ErrorMessage = "Category name must be between 2 and 80 characters.")]    public string Name { get; init; } = string.Empty;    public int? ParentCategoryId { get; init; }    public IEnumerable Validate(ValidationContext validationContext)    {        if (ParentCategoryId is not null && ParentCategoryId.Value <= 0)        {            yield return new ValidationResult(                "ParentCategoryId must be greater than zero.",                new[] { nameof(ParentCategoryId) });        }    } } public sealed class CreateCustomerRequest : IValidatableObject {    [Required(ErrorMessage = "First name is required.")]    [StringLength(60, MinimumLength = 2)]    public string FirstName { get; init; } = string.Empty;    [Required(ErrorMessage = "Last name is required.")]    [StringLength(60, MinimumLength = 2)]    public string LastName { get; init; } = string.Empty;    [Required(ErrorMessage = "Email is required.")]    [EmailAddress(ErrorMessage = "Email format is invalid.")]    [StringLength(255)]    public string Email { get; init; } = string.Empty;    [DataType(DataType.Date)]    public DateOnly? BirthDate { get; init; }    public IEnumerable Validate(ValidationContext validationContext)    {        if (BirthDate > DateOnly.FromDateTime(DateTime.UtcNow))        {            yield return new ValidationResult(                "BirthDate cannot be in the future.",                new[] { nameof(BirthDate) });        }    } }

IValidatableObject lets us access the complete object instead of evaluating only one property. It is appropriate for fast, local rules. Checks such as email uniqueness or whether a parent category exists should remain in the data-access or service layer.

4. Create a custom ValidationAttribute

When a rule is reused across multiple DTOs, a custom attribute is often a better solution. For example, require SKUs to use a standardized format.

using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; public sealed partial class ProductCodeAttribute : ValidationAttribute {    protected override ValidationResult? IsValid(        object? value,        ValidationContext validationContext)    {        if (value is not string code || string.IsNullOrWhiteSpace(code))        {            return ValidationResult.Success;        }        return ProductCodeRegex().IsMatch(code)            ? ValidationResult.Success            : new ValidationResult(                ErrorMessage ?? "Product code format is invalid.");    }    [GeneratedRegex("^[A-Z]{2,5}-[0-9]{3,10}$")]    private static partial Regex ProductCodeRegex(); }

Use the attribute on the DTO:

[Required] [ProductCode(ErrorMessage = "SKU must look like API-100.")] public string Sku { get; init; } = string.Empty;

Avoid database queries inside a custom attribute. Calling SkuExistsAsync from an attribute can create uncontrolled I/O every time validation runs. It also makes dependency injection and testing unnecessarily complicated.

5. Automatic 400 responses with ApiController

For controller-based ASP.NET Core Web APIs, applying [ApiController] causes model-binding and model-validation errors to be rejected before the action executes.

[ApiController] [Route("api/products")] public sealed class ProductsController : ControllerBase {    [HttpPost]    public async Task Create(        CreateProductRequest request,        CancellationToken cancellationToken)    {        // DataAnnotations rules have already passed at this point.        // Database-backed rules are checked below.        return Ok();    } }

The default response is a ValidationProblemDetails object. It contains fields such as status, title, traceId, and an errors dictionary keyed by field name. This allows client applications to determine which fields failed and why.

HTTP/1.1 400 Bad Request Content-Type: application/problem+json {  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",  "title": "One or more validation errors occurred.",  "status": 400,  "errors": {    "name": ["Product name is required."],    "price": ["Price must be between 0.01 and 1000000."]  } }

In this configuration, repeatedly writing if (!ModelState.IsValid) inside every action is unnecessary. Controllers can focus on requests that have passed structural validation.

6. Standardize validation responses

Different controllers should not return different error formats. If one action returns BadRequest(ModelState), another returns a plain string, and a third returns custom JSON, client applications become unnecessarily complex. Configure automatic 400 responses once at startup.

using Microsoft.AspNetCore.Mvc; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(options => {    options.ModelMetadataDetailsProviders.Add(        new SystemTextJsonValidationMetadataProvider()); }); builder.Services.Configure<ApiBehaviorOptions>(options => {    options.InvalidModelStateResponseFactory = context =>    {        var problemDetails = new ValidationProblemDetails(context.ModelState)        {            Status = StatusCodes.Status400BadRequest,            Title = "Request validation failed.",            Type = "https://api.example.com/problems/validation"        };        return new BadRequestObjectResult(problemDetails)        {            ContentTypes = { "application/problem+json" }        };    }; }); var app = builder.Build(); app.MapControllers(); app.Run();

SystemTextJsonValidationMetadataProvider helps produce validation keys using JSON property names rather than C# property names. If the client sends firstName, seeing firstName in the error dictionary is usually more consistent.

7. Uniqueness checks and the service layer

Fields such as SKU, category name, and customer email should have unique indexes or constraints in the database. The application-level check gives the client an early and understandable error; the database constraint remains the final protection against concurrent requests.

public async Task<ActionResult<ProductResponse>> Create(    CreateProductRequest request,    CancellationToken cancellationToken) {    var normalizedSku = request.Sku.Trim().ToUpperInvariant();    if (await productRepository.ExistsBySkuAsync(        normalizedSku, cancellationToken))    {        ModelState.AddModelError(            nameof(request.Sku),            "A product with this SKU already exists.");        return ValidationProblem(ModelState);    }    var categoryExists = await categoryRepository.ExistsAsync(        request.CategoryId!.Value, cancellationToken);    if (!categoryExists)    {        ModelState.AddModelError(            nameof(request.CategoryId),            "The specified category does not exist.");        return ValidationProblem(ModelState);    }    var product = new Product    {        Name = request.Name.Trim(),        Sku = normalizedSku,        Price = request.Price,        DiscountPercentage = request.DiscountPercentage,        CategoryId = request.CategoryId.Value    };    await productRepository.AddAsync(product, cancellationToken);    return CreatedAtAction(nameof(GetById), new { id = product.Id }, product); }

Even after this check, two concurrent requests can pass the existence query with the same SKU. For that reason, SQL Server must also have a unique index or unique constraint. A database-constraint exception should be handled by the centralized error-handling layer and translated into an appropriate problem response.

8. Common mistakes

  • Binding entities directly: Use request DTOs so clients can submit only fields they are allowed to change.
  • Duplicating messages in actions: Move repeated rules into attributes or reusable validators.
  • Putting asynchronous database checks in attributes: Perform uniqueness and existence checks in the service layer.
  • Relying only on application checks: Without a unique index, race conditions can still create duplicate records.
  • Returning 500 for every failure: Invalid client data is generally a 400, authentication problems are 401, authorization problems are 403, and missing resources are 404.
  • Ignoring empty strings and nulls: Define trimming and whitespace behavior explicitly, especially for string properties.

9. Short practice exercise

Implement the following scenario:

  1. Add a Description property to CreateProductRequest and allow at most 500 characters.
  2. Apply a custom attribute that requires the ABC-100 SKU format.
  3. When a SKU already exists, call ModelState.AddModelError and return ValidationProblem(ModelState) from the controller.
  4. Test the expected 400 responses for a missing product name, negative price, invalid SKU, and duplicate SKU.
  5. Verify that a valid request returns 201 and the URL of the created resource.

A good validation system does more than reject invalid data. It clearly explains which field failed, why it failed, and how the client can correct it.

Conclusion

In this lesson, we made model validation a central part of the API contract. We used DataAnnotations for basic rules, IValidatableObject for cross-field conditions, and a custom attribute for reusable format validation. Database-backed uniqueness and foreign-key checks were moved to the service layer. With [ApiController] and InvalidModelStateResponseFactory, all invalid requests can produce consistent 400 and ValidationProblemDetails responses.

In the next stage, we will extend this error format with centralized exception handling and a broader ProblemDetails infrastructure. This will allow not only validation failures but also unexpected application errors to be exposed safely and consistently to clients.

Sources