Code review of API response contracts: data exposure from returning entities, over-posting, unbounded lists, money as double, dates without offsets, inconsistent naming and internal ids, with a DTO-based rewrite.
Ranked by severity:
PasswordHash and internal flags. That's a security finding and, for personal data, a Privacy Act issue. Binding entities from requests also enables over-posting.double money loses precision (use decimal, send amounts as strings or minor units with an ISO 4217 currency); DateTime without an offset is ambiguous across Australian time zones (use DateTimeOffset).The fix is purpose-built request and response DTOs, projected in the query, with one JSON naming policy and cursor pagination. The trade-off is mapping code, which is cheap next to an incident.
"I'd rank these by blast radius. The worst is returning EF Core entities directly. The serialiser writes every public property, so
PasswordHash,IsFraudFlagged, internal notes and anything added to the entity later go to every client. That's a security finding on day one and, because it's personal information, a potential notifiable data breach under the Privacy Act. The same entity used as a request body enables over-posting: a client sendsisAdmin: trueand model binding happily sets it. Second is the list endpoint with no page-size limit. One request for all customers loads the table into memory, serialises it, and can take the instance down, so that's an availability problem anyone can trigger.Then the wrong-data issues. Money as
doubleis binary floating point, so 0.1 plus 0.2 isn't 0.3, and totals drift by cents, which finance will find. Usedecimalin C#, and on the wire send the amount as a string or as integer minor units with an ISO 4217 currency code, because JavaScript clients parse JSON numbers as doubles anyway. Dates asDateTimewith no offset are ambiguous: is 9:00 Sydney time, Perth time or UTC? UseDateTimeOffsetand ISO 8601 with an offset. For example, at [company] we [had an order cut-off bug where Western Australian customers saw times three hours off] because [the API emitted unspecifiedDateTimevalues], which took [a week] to untangle.Finally the contract hygiene: mixed PascalCase and snake_case means generated clients get ugly, inconsistent models, so pick camelCase via
JsonSerializerDefaults.Weband stick to it. Sequentialintids let anyone enumerate/customers/1,/customers/2and couple clients to your database; I'd expose a public id and always authorise per resource anyway. The rewrite is purpose-built DTOs, projected in the query withSelectso we never load what we don't return, plus cursor pagination with a capped page size."
// Customer entity used directly as the API contract
public class Customer
{
public int Id { get; set; } // 5 sequential DB id exposed
public string FullName { get; set; } = "";
public string email_address { get; set; } = ""; // 4 inconsistent naming
public string PasswordHash { get; set; } = ""; // 1 sensitive field serialised
public bool IsAdmin { get; set; } // 1 over-posting target
public double CreditLimit { get; set; } // 3 money as double
public DateTime CreatedAt { get; set; } // 3 no offset
public List<Order> Orders { get; set; } = []; // 1 lazy graph, cycles
}
app.MapGet("/customers", async (AppDb db) =>
await db.Customers.Include(c => c.Orders).ToListAsync()); // 2 unbounded, whole graph
app.MapPut("/customers/{id}", async (int id, Customer input, AppDb db) =>
{
db.Update(input); // 1 over-posting: IsAdmin, PasswordHash
await db.SaveChangesAsync();
return Results.Ok(input);
});
| # | Severity | Finding | Impact |
|---|---|---|---|
| 1 | Security | Entity returned and bound: PasswordHash, IsAdmin exposed and writable |
Credential exposure, privilege escalation, Privacy Act breach |
| 2 | Availability | ToListAsync() with no limit, Include of whole graph |
Memory blow-up, timeouts, easy denial of service |
| 3 | Wrong data | double money, DateTime without offset |
Rounding errors in totals; wrong times across time zones |
| 4 | Contract | Mixed naming (FullName, email_address) |
Inconsistent generated clients, frequent client bugs |
| 5 | Design | Sequential DB ids, no per-resource authorisation shown | Enumeration (BOLA), coupling to storage |
Separate DTOs, projection, capped cursor pagination and a narrow update command. Full code in the code example section.
Domain or Data namespace; Spectral rules for camelCase and format: date-time; a checklist item for page-size limits.In a similar review, the customer endpoint was returning [about 40] properties per record including a password hash; after the rewrite the response had [9] fields, payload size dropped by [80]%, and p95 latency on the list fell from [1.2 s] to [90 ms] because projection stopped loading the orders graph.
Checks that the candidate can review an API contract for security, availability and correctness issues, rank them sensibly and propose a robust DTO design.
Green flags
double and unspecified DateTime are wrong, with the fixRed flags
[JsonIgnore] onlyEF Core entity ──────► System.Text.Json ──────► client
(every public property, (serialises all (now depends on all of it,
navigation properties, public properties) including fields you'll
fields added next sprint) want to remove)
An entity is shaped for persistence and the domain; a DTO is shaped for one client use case. Coupling them means every schema change is an API change, and every sensitive column added later is exposed by default. OWASP API Security Top 10 calls this Broken Object Property Level Authorization (excessive data exposure plus mass assignment).
Model binding sets any property present in the JSON. With an entity as input:
PUT /customers/42
{ "fullName": "Jane", "isAdmin": true, "passwordHash": "..." }
db.Update(input) marks every property modified, so it also overwrites columns the client didn't send with defaults. The fix is a request DTO containing only editable fields, and applying them to a loaded entity.
| Representation | Precision | Client safety |
|---|---|---|
double / JSON number from double |
Binary floating point; 0.1 not exact | Rounding errors |
decimal as JSON number |
Exact in .NET | JavaScript parses into a double: risk above 2^53 or with many decimals |
Amount as string "120.50" + currency |
Exact | Safe everywhere |
Minor units 12050 + currency |
Exact integer | Safe; clients must know the exponent (AUD 2, JPY 0) |
Always include the ISO 4217 currency code, even if you only deal in AUD today.
DateTime has a Kind (Utc, Local, Unspecified). System.Text.Json writes Unspecified without an offset, so 2026-11-20T09:00:00 reaches clients as an ambiguous local time. Australia has several offsets (AEST/AEDT, ACST/ACDT, AWST), and Queensland has no daylight saving, so ambiguity causes real bugs. Use DateTimeOffset for instants, DateOnly for dates like a birthday, and send IANA time zone ids (Australia/Perth) when a local time matters.
Sequential ids leak volume ("order 10,482 means they've had ten thousand orders") and invite enumeration. A public id (GUID v7 or a prefixed opaque id like cus_8f3k...) avoids that, but it is not authorisation. Every request must still check the caller can access that resource (OWASP API1: Broken Object Level Authorization).
Select into a DTO lets EF Core generate SQL for only the needed columns and no Include. That's both safer and faster than loading entities and mapping in memory.
PasswordHash from a Minimal API and look at the JSON; then switch to a DTO.isAdmin: true to an endpoint bound to the entity and observe it saved.0.1 ten times as double and as decimal and compare.DateTime.Now, DateTime.UtcNow and DateTimeOffset.Now with System.Text.Json and compare the output.Data namespace.The rewrite: response and request DTOs, projection, safe money and dates, capped pagination and a narrow update.
// Customers/CustomerContracts.cs
namespace Shop.Api.Customers;
public sealed record MoneyDto(string Amount, string Currency); // "5000.00", "AUD"
public sealed record CustomerDto(
string Id, // public id, not the database key
string FullName,
string Email,
MoneyDto CreditLimit,
DateTimeOffset CreatedAt); // ISO 8601 with offset
public sealed record UpdateCustomerRequest(string FullName, string Email); // only editable fields
public sealed record CustomerPage(IReadOnlyList<CustomerDto> Items, string? NextCursor);
// Customers/CustomerEndpoints.cs
using System.Globalization;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
namespace Shop.Api.Customers;
public static class CustomerEndpoints
{
private const int MaxLimit = 100;
public static void MapCustomers(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/v1/customers").RequireAuthorization("customers:read");
group.MapGet("/", async (int? limit, string? after, AppDb db, CancellationToken ct) =>
{
var take = Math.Clamp(limit ?? 25, 1, MaxLimit); // capped page size
var afterId = CursorCodec.Decode(after); // opaque cursor -> internal key
var rows = await db.Customers.AsNoTracking()
.Where(c => afterId == null || c.Id > afterId)
.OrderBy(c => c.Id)
.Take(take + 1)
// Projection: only these columns are queried; PasswordHash never leaves the database.
.Select(c => new { c.Id, c.PublicId, c.FullName, c.Email, c.CreditLimit, c.CreatedAt })
.ToListAsync(ct);
var hasMore = rows.Count > take;
var page = rows.Take(take).Select(c => new CustomerDto(
c.PublicId, c.FullName, c.Email,
new MoneyDto(c.CreditLimit.ToString("0.00", CultureInfo.InvariantCulture), "AUD"),
c.CreatedAt)).ToList();
return TypedResults.Ok(new CustomerPage(page, hasMore ? CursorCodec.Encode(rows[take - 1].Id) : null));
});
group.MapPut("/{publicId}", async Task<Results<NoContent, NotFound>> (
string publicId, UpdateCustomerRequest req, AppDb db, CancellationToken ct) =>
{
var customer = await db.Customers.SingleOrDefaultAsync(c => c.PublicId == publicId, ct);
if (customer is null) return TypedResults.NotFound();
// Per-resource authorisation check would go here (caller owns or may manage this customer).
// Apply only editable fields: no IsAdmin, no PasswordHash, no over-posting.
customer.FullName = req.FullName;
customer.Email = req.Email;
await db.SaveChangesAsync(ct);
return TypedResults.NoContent();
}).RequireAuthorization("customers:write");
}
}
// Data/Customer.cs - the entity stays internal to persistence.
namespace Shop.Api.Data;
public sealed class Customer
{
public int Id { get; set; }
public string PublicId { get; set; } = "";
public string FullName { get; set; } = "";
public string Email { get; set; } = "";
public string PasswordHash { get; set; } = "";
public bool IsAdmin { get; set; }
public decimal CreditLimit { get; set; } // decimal(18,2) in SQL Server
public DateTimeOffset CreatedAt { get; set; } // datetimeoffset
}
[JsonIgnore] on the entity as the fix. Why it is wrong: It's opt-out security: the next sensitive column is exposed by default. Instead: Opt-in DTOs that list exactly what is returned.db.Update. Why it is wrong: Over-posting sets fields like IsAdmin and overwrites unsent columns. Instead: Request DTOs with only editable fields, applied to a loaded entity.double for money. Why it is wrong: Binary floating point can't represent most decimal fractions. Instead: decimal in C#, string or minor units plus currency on the wire.DateTime with Kind = Unspecified in responses. Why it is wrong: Clients guess the time zone, and Australia has several. Instead: DateTimeOffset and ISO 8601 with an offset.Select inside the LINQ query so EF Core emits one SQL statement; for nested collections in the DTO, check the generated SQL and consider AsSplitQuery.Contract mistakes are cheap to fix before release and expensive after, because every one of these fixes is a breaking change once clients depend on the bad shape. That's why I treat money format, date format and naming as blocking on a public API even though they look cosmetic. Data exposure and unbounded queries are blocking everywhere. My position is simple: entities are never the API contract, not even "temporarily", because temporary contracts become permanent the day a client integrates.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Hand-written DTOs + Select projection |
Every API | Mapping code | Never skip for real endpoints |
| Mapping libraries (Mapperly source generator) | Many similar DTOs | Build-time generator; less visible mappings | When explicit mapping is short |
Entity as contract with [JsonIgnore] |
Not recommended: opt-out security | Exposure by default, schema coupling | Any real API, especially with personal data |
| Public ids (GUID v7, prefixed ids) | Public APIs, enumeration concerns | Extra column and index | Purely internal service-to-service APIs |
Security checks sit alongside the DTOs, not instead of them: authentication on the group, a scope or policy per operation, and a per-resource ownership check in the handler before any data is read. To stop the pattern recurring I prefer automated checks over reviewer vigilance: an architecture test banning domain or data types in endpoint signatures, Spectral rules on the generated spec, and a review checklist covering page limits, money and dates.
A domain model represents business concepts with behaviour and invariants (an Order that can be paid, cancelled, and refuses invalid changes). A DTO (data transfer object) is a flat, behaviour-free contract for moving data across a boundary: an HTTP request or response, a message, a query result. Keep them separate so that the API contract and the domain can change independently, so clients cannot over-post fields they must not set (IsAdmin, Status), and so internal data does not leak in responses. Map with explicit code, source-generated mappers (Mapperly) or EF Core projections straight to DTOs for reads. Sharing one type is acceptable only for simple CRUD with no rules, and even then be careful at public boundaries.
Ranked by severity: (1) over-posting: binding the EF entity lets a client set fields they shouldn't (IsApproved, Role, Price, Id, navigation properties), a security hole. (2) information disclosure: returning ex.Message can leak SQL, server names or personal data. (3) broken HTTP semantics: 200 with success: false makes failures look like successes to monitoring, retries, caches and clients. (4) swallowed exceptions: the catch-all hides bugs and usually doesn't log. (5) hand-rolled validation: inconsistent and duplicated. The rewrite: a request DTO with only the allowed fields, DataAnnotations with [ApiController] (or FluentValidation), explicit mapping to the entity, proper status codes (201, 400, 404, 409) via ProblemDetails, and global exception handling with UseExceptionHandler instead of try/catch in every action.
Offset pagination (?page=3&pageSize=50) is simple and allows jumping to page N, but SQL Server still reads and discards every skipped row, so deep pages get slower, and inserts or deletes shift rows between pages, giving duplicates and gaps.
Cursor (keyset) pagination (?after=eyJ...) remembers the last row's sort key and seeks past it, so every page costs the same and pages stay stable while data changes. The cursor should be opaque and the sort must end in a unique tie-breaker.
I return items plus a next link or nextCursor, enforce a maximum page size, and make total counts optional, because COUNT(*) over a large filtered set is a second query that can cost more than the page itself. The trade-off: cursors can't jump to an arbitrary page.
How to tell it (STAR)
**S:** A penetration test found our customer API returning password hashes and fraud flags, because endpoints returned EF Core entities directly, and the list endpoint had no limit. **T:** I led the fix and the review of how it happened. **A:** I shipped a same-day hotfix with DTOs and a page cap, worked with [our privacy officer] on the breach assessment, then rewrote the contracts with request DTOs, projection, cursor paging, string money and offset dates, and added an architecture test so entities can't be returned again. **R:** The retest passed, list p95 dropped from [1.2 s] to [90 ms], and the architecture test has since blocked [three] attempts to return entities.
Last updated 23 Nov 2026.