ASP.NET Core Web API Interview Question #50
What are best practices for DTOs, model binding, validation, and API responses?
DTOs, Model Binding, Validation & API Responses Junior Beginner
Quick Interview Answer
Use purpose-specific request and response DTOs instead of exposing persistence entities. Make binding sources clear, validate input at the API boundary, and keep database-dependent or domain validation in appropriate application services.
Detailed Explanation
Use purpose-specific request and response DTOs instead of exposing persistence entities. Make binding sources clear, validate input at the API boundary, and keep database-dependent or domain validation in appropriate application services.
Use ApiController conventions intentionally, return meaningful HTTP status codes, prefer consistent ProblemDetails-based error responses, and use ActionResult<T> where it clarifies the successful response contract. Paginate large collections, validate query parameters, and keep the public API contract stable and independent from internal storage models.
Code Example
[HttpPost]
public async Task<ActionResult<ProductResponse>> Create(
CreateProductRequest request,
CancellationToken token)
{
var result = await _service.CreateAsync(request, token);
if (!result.Succeeded)
return Problem(
statusCode: 409,
title: result.Error);
return CreatedAtAction(
nameof(GetById),
new { id = result.Value.Id },
result.Value);
}