Debugging silent model binding failures in ASP.NET Core: 415 from a wrong or missing Content-Type, null bodies from JSON errors or empty bodies, default values from casing or naming mismatches, enums as strings without JsonStringEnumConverter, number/string and date format mismatches, missing [FromBody] or [ApiController], and the tools to see the real error (ModelState, ThrowOnBadRequest, Debug logging, request logging).
I start by capturing the exact raw request, because the cause is almost always in the headers or the JSON. A 415 means the Content-Type is missing or isn't application/json. A null object means the body was empty or invalid JSON, or the deserialisation error went into ModelState and nobody looked (controllers without [ApiController]). Default values mean the JSON didn't match: property names (customer_id vs customerId), enums as strings without JsonStringEnumConverter, a wrapper object, fields instead of properties. To see the real error, I turn on Debug logging for Microsoft.AspNetCore.Mvc/Microsoft.AspNetCore.Http, use ThrowOnBadRequest for Minimal APIs, and check which JsonOptions the endpoint actually uses. I prevent it with [ApiController], required members, contract tests and generated clients. The trade-off: lenient binding hides bugs; strict binding surfaces them as 400s.
"Silent binding failures are frustrating because the framework did exactly what it was told. So I don't guess; I get the exact request. I'll turn on
UseHttpLoggingwith request headers and body in a test environment, or ask for the curl command, or look at the browser's Network tab. Nine times out of ten the answer is in the headers or the JSON.Then I map symptoms to causes. A 415 means the content type: a client sending
text/plainfromfetchwithout headers, orapplication/x-www-form-urlencodedfrom a form. A null DTO in a controller usually means the JSON didn't deserialise, and without[ApiController]that error sits inModelStatewhile the action runs anyway. Default values on some properties mean names or types don't match: the client sendscustomer_idand we expect camelCase, or sends"status": "Shipped"when we didn't registerJsonStringEnumConverter, or wraps everything in{ "order": { ... } }. In a Minimal API I setThrowOnBadRequestso the exception tells me exactly which parameter failed and why, and I raise logging forMicrosoft.AspNetCore.HttpandMicrosoft.AspNetCore.Mvcto Debug.For example, [at company] a partner integration [created orders with zero quantities for a day]. The request logs showed
"Quantity": "5"with a string, which was fine, but"order_lines"in snake_case, so ourOrderLinesstayed empty and validation didn't require it. We added[ApiController]-style strictness, markedLinesasrequiredwith a minimum count so missing data became a 400, and gave the partner a generated client from our OpenAPI document. [Bad orders dropped to zero]. The mistake I see is making binding more lenient to 'fix' it; the senior fix is making missing data fail loudly."
| Symptom | Likely cause | Fix |
|---|---|---|
| 415 Unsupported Media Type | Missing or wrong Content-Type |
Client sends application/json |
| DTO is null (controller) | Invalid JSON or empty body; no [ApiController] |
Add [ApiController]; inspect ModelState |
| 400 "The JSON value could not be converted" | Type mismatch: enum string, date format, number overflow | JsonStringEnumConverter, ISO 8601 dates, correct types |
| Some properties default | Naming mismatch, wrapper object, fields, no setter | Match naming policy, [JsonPropertyName], properties with init |
| Works in Postman, not in app | App sends form data or different casing | Compare raw requests |
| Config change had no effect | Changed MVC JsonOptions but endpoint is a Minimal API (or vice versa) |
Configure the right options |
| Complex parameter null in Minimal API | Expected from query but bound from body | [AsParameters] or [FromQuery] |
| Tool | What it shows |
|---|---|
UseHttpLogging (test only) |
Raw headers and body |
ThrowOnBadRequest |
Exact parameter and reason (Minimal APIs) |
Debug logs Microsoft.AspNetCore.Mvc.ModelBinding |
Which binder and source were used |
ModelState in a breakpoint |
Deserialisation errors (MVC) |
WebApplicationFactory test with the raw JSON |
Reproducible case |
Marking request DTO members as required (with JsonSerializerOptions.RespectRequiredConstructorParameters and RespectNullableAnnotations in .NET 9+) turned silent defaults into 400s listing the missing fields; the first week surfaced two partner clients sending wrong property names, which were fixed before they caused bad data.
Checks a methodical approach to a common, frustrating production issue and knowledge of System.Text.Json behaviour.
Green flags
JsonOptions types.Red flags
HTTP request
├─ Content-Type check ───────────────────────────► 415
├─ Read body (empty?) ───────────────────────────► null / 400
├─ System.Text.Json deserialise
│ ├─ syntax error / type conversion error ────► JsonException → 400 or ModelState
│ └─ unknown property names ──────────────────► ignored silently (default)
└─ Validation ─────────────────────────────────────► 400 (if configured)
The silent case is the third bullet: System.Text.Json ignores unknown members by default, so a wrong name just leaves the property at its default.
JsonSerializerDefaults.Web: PropertyNameCaseInsensitive = true, PropertyNamingPolicy = CamelCase, NumberHandling = AllowReadingFromString. So CustomerId, customerId and CUSTOMERID all bind, but customer_id does not (unless you use JsonNamingPolicy.SnakeCaseLower, .NET 8+). Enums are numbers unless JsonStringEnumConverter is added. Dates must be ISO 8601.
required members and [JsonRequired]: missing properties throw a JsonException → 400.JsonUnmappedMemberHandling.Disallow (.NET 8+): unknown properties fail instead of being ignored. Great for catching typos; use carefully on public APIs where clients may send extra fields.RespectNullableAnnotations (.NET 9+): null for a non-nullable reference type fails.[ApiController] and .NET 10 AddValidation() turn these into 400 ProblemDetails.[ApiController]: the input formatter catches JsonException, adds it to ModelState, and the parameter is null; the action runs.BadHttpRequestException when ThrowOnBadRequest is on). An empty body for a non-nullable parameter is a 400.AddHttpLogging(o => o.LoggingFields = HttpLoggingFields.RequestHeaders | HttpLoggingFields.RequestBody) with RequestBodyLogLimit. Use it only in test environments or with redaction: request bodies often contain personal information (APP 11).
{"customer_id": 5} to an endpoint expecting CustomerId and observe the default; add JsonUnmappedMemberHandling.Disallow and retry.JsonStringEnumConverter.[ApiController] and post invalid JSON; inspect ModelState in the debugger.ThrowOnBadRequest on a Minimal API and read the exception for a bad body.JsonStringEnumConverter only in AddJsonOptions and test both a controller and a Minimal API.Strict JSON settings for both models, required members, and safe request logging for diagnosis.
// Program.cs
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.HttpLogging;
var builder = WebApplication.CreateBuilder(args);
static void Strict(JsonSerializerOptions o)
{
o.Converters.Add(new JsonStringEnumConverter()); // "Shipped" binds to OrderStatus.Shipped
o.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow; // typos like customer_id fail loudly
o.RespectNullableAnnotations = true; // null for non-nullable members fails (.NET 9+)
}
// Configure BOTH option types so controllers and Minimal APIs behave the same
builder.Services.ConfigureHttpJsonOptions(o => Strict(o.SerializerOptions));
builder.Services.AddControllers().AddJsonOptions(o => Strict(o.JsonSerializerOptions));
// Minimal APIs: throw with a precise message instead of a bare 400 (Development only)
builder.Services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = builder.Environment.IsDevelopment());
if (builder.Environment.IsEnvironment("Test"))
{
// Raw request capture for diagnosis; never log bodies with personal data in production
builder.Services.AddHttpLogging(o =>
{
o.LoggingFields = HttpLoggingFields.RequestMethod | HttpLoggingFields.RequestPath |
HttpLoggingFields.RequestHeaders | HttpLoggingFields.RequestBody;
o.RequestBodyLogLimit = 4 * 1024;
o.MediaTypeOptions.AddText("application/json");
});
}
var app = builder.Build();
if (app.Environment.IsEnvironment("Test")) app.UseHttpLogging();
app.MapPost("/orders", (CreateOrder cmd) => TypedResults.Ok(cmd));
app.MapControllers();
app.Run();
public enum OrderStatus { Draft, Submitted }
// required: a missing property is a 400, not a silent default
public sealed record CreateOrder
{
public required string CustomerId { get; init; }
public required IReadOnlyList<OrderLine> Lines { get; init; }
public OrderStatus Status { get; init; } = OrderStatus.Draft;
}
public sealed record OrderLine(string Sku, int Quantity);
// appsettings.Development.json: see which binder and source were used, and why binding failed
{
"Logging": {
"LogLevel": {
"Microsoft.AspNetCore.Mvc.ModelBinding": "Debug",
"Microsoft.AspNetCore.Http": "Debug",
"Microsoft.AspNetCore.HttpLogging": "Information"
}
}
}
JsonOptions types. Instead: Configure both from one method.[ApiController] from controllers. Why it is wrong: Deserialisation errors go into ModelState and the action runs with null. Instead: Keep it, or check ModelState explicitly.init or constructor parameters only (fields need IncludeFields). Instead: Records or init properties.JsonUnmappedMemberHandling.Disallow on an existing public API without notice. Why it is wrong: Clients that send harmless extra fields start failing. Instead: Apply to new versions or internal APIs, or roll out with monitoring.Silent binding failures are a design smell: the API accepted a request it didn't understand. A senior fixes the specific bug and then makes the class of bug impossible, with strict deserialisation (required members, nullable annotations, optionally disallowing unknown members), [ApiController] or .NET 10 validation, and clients generated from the OpenAPI document so names and types can't drift. Diagnosis is evidence-first: capture the raw request, then read the framework's own Debug logs, which usually name the exact failure.
Tightening the contract is itself a change to the contract. Making a field required or rejecting unknown members can break clients that worked yesterday, so roll it out like any breaking change: publish the updated OpenAPI document, run consumer contract tests (partner sample payloads in CI, or Pact-style tests), apply strictness to a new API version or behind monitoring first, and give partners a deprecation window for the old behaviour.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
required members / [JsonRequired] |
Any DTO with mandatory data | None | Optional fields |
JsonUnmappedMemberHandling.Disallow |
Internal APIs, new versions | Breaks clients sending extras | Established public APIs without a version bump |
RespectNullableAnnotations |
.NET 9+ with nullable enabled | Stricter null handling | Legacy clients sending nulls |
| Generated clients (Kiota, NSwag) + contract tests | Partners and front ends | Build step | Truly ad hoc clients |
| Request body logging | Short diagnostic windows in test | Privacy risk | Production by default |
Model binding takes data from the request (route values, query string, headers, form fields, the JSON body) and from DI, converts it, and passes it to your handler's parameters. You can be explicit with [FromRoute], [FromQuery], [FromHeader], [FromForm], [FromBody] and [FromServices], or let the framework infer. In Minimal APIs: a parameter named in the route template comes from the route, other simple types from the query, registered services from DI, and complex types from the JSON body. In controllers with [ApiController]: complex types from the body, IFormFile from the form, route names from the route, the rest from the query. Only one parameter can read the body. [AsParameters] groups parameters into a record. The trade-off: inference keeps code short, but explicit attributes make the contract obvious in reviews and OpenAPI.
Two headers drive it: Content-Type says what format the request body is in, and Accept says which formats the client wants back. In MVC, input formatters are chosen by Content-Type (no match → 415) and output formatters by Accept, using quality values; if nothing matches, MVC falls back to the first formatter (JSON) unless ReturnHttpNotAcceptable is on, which returns 406. You add XML with AddXmlSerializerFormatters(). Minimal APIs don't negotiate: they read and write JSON only (415 for other body types), so other formats need a custom IResult. JSON settings are configured separately: AddJsonOptions for controllers and ConfigureHttpJsonOptions for Minimal APIs. The trade-off: negotiation gives flexibility for integrations, but most APIs are simpler and safer as JSON-only.
How to tell it (STAR)
**S:** A new partner created [about 300] empty orders in a day and our API returned 201 for every one. **T:** I had to find out why and stop it happening again. **A:** I replayed their payload with request logging in staging, saw snake_case names that System.Text.Json silently ignored, then made lines required with a minimum count, disallowed unknown members on the new version, and gave partners a generated client. **R:** Empty orders dropped to [zero], and the contract tests caught [two] more naming mismatches during later partner onboardings.
Last updated 23 Nov 2026.