In ASP.NET Core with EF Core, why does a PUT handler that binds the body to the Employee entity and calls db.Update let a caller rewrite Salary?
answer
- the body binds by property name
- omitted members arrive as defaults
- Update marks the whole entity Modified
- UpdateEmployeeRequest record plus FindAsync
- JsonUnmappedMemberHandling.Disallow rejects extras
basics
~20 sThe JSON body is deserialized straight onto Employee, so any property the caller sends, Salary included, is set, and any it omits arrives as a default. db.Update then marks every column modified, so SaveChanges writes both into the row.
solid answer
~50 sA Minimal API binds a complex body parameter with `System.Text.Json` (case-insensitive under the web defaults), and an `[ApiController]` action does the same through its JSON input formatter. If the parameter type is the `Employee` entity, a body containing `"salary": 250000` sets `Salary`; a body that leaves it out produces `Salary = 0`. `db.Employees.Update(employee)` puts the entity in the `Modified` state, so `SaveChangesAsync` writes **every** mapped column — the attacker's value or the zero. Attributes do not save you: `[BindNever]` belongs to MVC model binding and is not honoured for JSON bodies. The fix is an `UpdateEmployeeRequest` record with only the editable fields, then load the entity with `FindAsync`, copy those fields, and call `SaveChangesAsync`, which updates only what changed. An extra `salary` member in the body is then simply ignored, or rejected with 400 if the record carries `[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]`.
code
csharp · 16 linespublic sealed record UpdateEmployeeRequest(string FirstName, string LastName, string Email, int DepartmentId);
app.MapPut("/employees/{id:int}", async Task<Results<NoContent, NotFound>> (
int id, UpdateEmployeeRequest request, HrDb db) =>
{
var employee = await db.Employees.FindAsync(id);
if (employee is null) return TypedResults.NotFound();
employee.FirstName = request.FirstName;
employee.LastName = request.LastName;
employee.Email = request.Email;
employee.DepartmentId = request.DepartmentId;
await db.SaveChangesAsync(); // UPDATE only the changed columns
return TypedResults.NoContent();
});go deeper
Know that binding a request body onto the entity lets callers set any matching property, and that a request record with only editable fields prevents it.
Explain both halves: System.Text.Json fills by name and defaults omitted members, and DbSet.Update marks the whole entity Modified so SaveChanges writes every column.
Show the load-then-copy pattern, why [BindNever] and [JsonIgnore] are the wrong tools for JSON bodies, and when to make unknown members fail with Disallow.
Set the convention that every write endpoint has its own request type, and weigh that type count against the incidents a shared entity contract invites.
## The vulnerable handler ```csharp app.MapPut("/employees/{id:int}", async (int id, Employee employee, HrDb db) => { employee.Id = id; db.Employees.Update(employee); await db.SaveChangesAsync(); return TypedResults.NoContent(); }); ``` It looks economical: the form on the HR portal only edits name, e-mail and department, so the body only carries those. Two separate ASP.NET Core and EF Core mechanisms turn it into a hole. ## Mechanism 1: the body fills whatever matches A Minimal API parameter of a complex type with no binding attribute is read from the JSON body. The Request Delegate Factory hands the stream to **System.Text.Json** with the app's `JsonOptions`, whose web defaults match property names case-insensitively. So: - a body with `"salary": 250000` sets `Employee.Salary`, because the entity has a public settable `Salary`; - a body **without** `salary` leaves the property at its CLR default, `0m`; - unknown members are skipped by default (`JsonUnmappedMemberHandling.Skip`), so nothing in the request tells you a client sent more than the form does. An `[ApiController]` action with `[FromBody] Employee employee` behaves the same way through MVC's System.Text.Json input formatter. ## Mechanism 2: Update writes every column `DbSet<T>.Update` attaches the object and puts it in the **`Modified`** state as a whole. EF Core has no original values to compare against, so `SaveChangesAsync` issues an `UPDATE` that sets every mapped column from the object. Whatever `Salary` holds — the attacker's figure or the default zero — is written. That second case is **under-posting**: an honest client that omits a field wipes it. Both come from the same design choice: treating the persistence entity as the request contract. ## What does not fix it | Attempt | Why it falls short | |---|---| | `[BindNever]` on `Salary` | An MVC model-binding attribute; System.Text.Json body deserialization ignores it, and the Minimal API binding docs say not to use these attributes to prevent over-posting | | `[JsonIgnore]` on `Salary` | Stops reads and writes everywhere the entity is serialized, and is a deny-list the next sensitive column escapes | | Re-reading `Salary` after `Update` | Order-dependent patching that still writes every other column the client omitted | | Validation attributes | Check values, not which fields a caller may set | ## The fix: a request record and a load-then-copy update 1. Define the contract for this operation only: `public sealed record UpdateEmployeeRequest(string FirstName, string LastName, string Email, int DepartmentId);`. 2. Bind that record, not the entity. 3. Load the tracked entity with `await db.Employees.FindAsync(id)`; return `TypedResults.NotFound()` if it is missing. 4. Copy the allowed fields onto the entity, by hand or through a mapper method that maps onto an existing target. 5. Call `SaveChangesAsync()`. Change tracking compares current and original values and updates only the columns that actually changed; `Salary` is never touched because nothing in the code path can set it. Two optional hardening steps: - Put `[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]` on the request record. A body carrying `salary` then fails to deserialize, and a Minimal API answers **400** instead of silently dropping the member — useful when you want probing to be visible. - Give each operation its own record. A `CreateEmployeeRequest` and an `UpdateEmployeeRequest` differ (an HR admin may set a starting salary on create through a separate, authorized endpoint), and sharing one type re-creates the problem. ## Why this is asked in interviews It tests whether a candidate sees two layers at once: the binder fills by name and defaults the rest, and EF Core's `Update` turns that object into a full-row write. The right answer names the request record and the load-then-copy pattern, not an attribute.
- Why does the honest HR form, which never sends salary, still zero it in the vulnerable handler?System.Text.Json leaves an omitted member at its CLR default, so `Salary` is `0m` on the bound entity. `Update` marks the whole entity `Modified`, and `SaveChangesAsync` writes every mapped column from it, including that zero. Loading the entity and copying only the edited fields avoids it, because untouched properties keep their database values.
- What does [JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)] change on a request record?Deserialization throws a `JsonException` when the body has a member the record does not declare, such as `salary`. A Minimal API catches that and answers 400, so a client probing for extra fields is rejected visibly instead of having the member silently skipped, which is the default `Skip` behaviour.
- [BindNever] on Salary stops a JSON body from setting it
- db.Update only writes the properties the client actually sent
- A field missing from the JSON body leaves the database value unchanged
- Validation attributes on the entity prevent over-posting
- One shared EmployeeRequest type for create and update is good reuse