⚙️ The Request Body Looks Perfect – The Model Still Comes Back Null
You POST a well-formed JSON body to an endpoint, ModelState.IsValid says true, and yet the parameter your action method receives is null or has every property at its default value – no error, no exception, just quietly wrong data.
🐞 The Problem
public class CreateOrderRequest
{
public int CustomerId { get; } // <- no setter!
public List<string> Items { get; set; }
}
[HttpPost]
public IActionResult Create(CreateOrderRequest request)
{
// request.CustomerId is always 0, no matter what
// was sent in the JSON body
}
🔍 Why This Happens
ASP.NET Core's default JSON model binder (System.Text.Json) constructs the object and then sets each property individually via its SETTER. A property with a get-only accessor (no "set") simply can't be assigned this way, so it silently keeps its default value instead of throwing - the binder doesn't consider a missing setter an error, it just skips what it can't write to.
✅ The Fix: Give Every Bound Property a Setter, or Use a Constructor Binding Model
- Simplest: add a normal
{ get; set; }to every property that needs to come from the request body. - For immutable request models, use a C# record with a primary constructor instead – System.Text.Json supports binding directly through constructor parameters when property names match, keeping immutability without breaking binding.
- Turn on more visible binding diagnostics in development by logging
ModelStateerrors even whenIsValidis true for properties that stayed at their default — a silent skip is much harder to debug than an explicit warning.
📦 Correct Version (Record With Constructor Binding)
public record CreateOrderRequest(int CustomerId, List<string> Items);
[HttpPost]
public IActionResult Create(CreateOrderRequest request)
{
// request.CustomerId now correctly reflects the JSON body
}
Model binding fails quietly by design – it was built to tolerate a missing field, not to warn you that your own class shape made a field impossible to fill.
