ASP.NET Core Web API Interview Question #41

How should an API validate business rules that require database access?

DTOs, Model Binding, Validation & API Responses Junior Beginner

Quick Interview Answer

Perform database-dependent validation in the application or domain service rather than relying only on Data Annotations. For example, checking whether an email is already registered requires current application state.

Detailed Explanation

Perform database-dependent validation in the application or domain service rather than relying only on Data Annotations. For example, checking whether an email is already registered requires current application state.

Database constraints should still enforce critical integrity because two concurrent requests can both pass an application-level check before either commits.

Code Example

if (await _customers.EmailExistsAsync(
        request.Email, token))
{
    return Conflict(new ProblemDetails
    {
        Title = "Email already exists",
        Status = StatusCodes.Status409Conflict
    });
}