📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

A client says your API ignores their data: the request object arrives as null or with default values, or they get a 415, and nothing in the logs explains it. Possible causes include JSON casing, enums sent as strings, a missing [FromBody], the wrong Content-Type, and type mismatches. How do you diagnose and fix it?

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).

Mid-Level Debugging Intermediate aspnet-core debugging model-binding request-handling system-text-json

🎯 Key points

  • First capture the exact raw request (method, headers, body) with HTTP logging, a proxy, or browser dev tools
  • 415: Content-Type missing or not application/json (Minimal APIs and MVC both require a JSON content type for JSON bodies)
  • Null body: invalid JSON, an empty body, or a deserialisation error swallowed into ModelState (MVC without [ApiController])
  • Default values: property name mismatch (snake_case vs camelCase), fields instead of properties, a wrapping root object; System.Text.Json ignores unknown members silently
  • Enums as strings fail without JsonStringEnumConverter; numbers in quotes need AllowReadingFromString (on by default for web defaults)
  • Validation is the safety net: required members and [Required]/minimum counts turn missing data into a 400 instead of a silent default
  • Turn on Debug logging for Microsoft.AspNetCore.Mvc and Microsoft.AspNetCore.Http and RouteHandlerOptions.ThrowOnBadRequest, and check which JsonOptions the endpoint uses
  • Prevent with contract tests, an OpenAPI document as the published contract, generated clients, and versioning when tightening rules

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 UseHttpLogging with 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/plain from fetch without headers, or application/x-www-form-urlencoded from a form. A null DTO in a controller usually means the JSON didn't deserialise, and without [ApiController] that error sits in ModelState while the action runs anyway. Default values on some properties mean names or types don't match: the client sends customer_id and we expect camelCase, or sends "status": "Shipped" when we didn't register JsonStringEnumConverter, or wraps everything in { "order": { ... } }. In a Minimal API I set ThrowOnBadRequest so the exception tells me exactly which parameter failed and why, and I raise logging for Microsoft.AspNetCore.Http and Microsoft.AspNetCore.Mvc to 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 our OrderLines stayed empty and validation didn't require it. We added [ApiController]-style strictness, marked Lines as required with 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 → cause → fix

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]

Tools

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

Production example

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.

🔍 What the interviewer is checking

Checks a methodical approach to a common, frustrating production issue and knowledge of System.Text.Json behaviour.

Green flags

  • Starts by capturing the raw request.
  • Maps 415, null and default-value symptoms to specific causes.
  • Knows the web defaults, enum handling and the two JsonOptions types.
  • Prevents recurrence with strictness and generated clients.

Red flags

  • Guesses and changes code without seeing the request.
  • Logs full bodies in production.
  • Makes binding more lenient as the fix.

📚 Learn in depth

1. Where binding can fail

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.

2. System.Text.Json web defaults

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.

3. Making it strict

  • 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.

4. MVC vs Minimal APIs

  • MVC without [ApiController]: the input formatter catches JsonException, adds it to ModelState, and the parameter is null; the action runs.
  • Minimal APIs: a body that fails to deserialise produces a 400 (or throws BadHttpRequestException when ThrowOnBadRequest is on). An empty body for a non-nullable parameter is a 400.

5. Logging the request safely

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).

Try it yourself

  1. Post {"customer_id": 5} to an endpoint expecting CustomerId and observe the default; add JsonUnmappedMemberHandling.Disallow and retry.
  2. Post an enum as a string with and without JsonStringEnumConverter.
  3. Remove [ApiController] and post invalid JSON; inspect ModelState in the debugger.
  4. Enable ThrowOnBadRequest on a Minimal API and read the exception for a bad body.
  5. Configure JsonStringEnumConverter only in AddJsonOptions and test both a controller and a Minimal API.

💻 Code

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"
    }
  }
}

⚠ Common mistakes

  • Mistake: Making binding more lenient to 'fix' missing data. Why it is wrong: Bad data flows into the system silently. Instead: Make required data required so the client gets a 400.
  • Mistake: Configuring JSON options for the wrong model. Why it is wrong: Minimal APIs and controllers use different JsonOptions types. Instead: Configure both from one method.
  • Mistake: Removing [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.
  • Mistake: Logging full request bodies in production to debug. Why it is wrong: Bodies contain personal and payment data; it breaches APP 11 and PCI expectations. Instead: Reproduce in test, or log with redaction and size limits for a short window.
  • Mistake: Assuming Postman success means the client is fine. Why it is wrong: Real clients may send different headers, casing or form data. Instead: Capture and compare the client's raw request.
  • Mistake: Using fields or get-only properties without constructors on DTOs. Why it is wrong: System.Text.Json binds public properties with setters, init or constructor parameters only (fields need IncludeFields). Instead: Records or init properties.
  • Mistake: Turning on 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions a missing [FromBody] or a complex type bound from the wrong source. Why: Checks the binding source inference rules behind many of these failures.
    How to answer

    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.

  2. When: Candidate mentions 415 or JsonOptions. Why: Checks Content-Type, formatters and the separate JSON options.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Partner orders created with no lines because of snake_case JSON
Situation
A B2B ordering API [at company] received orders from [about 40] partners. A new partner integration went live on [a Monday].
Signals
The warehouse received [~300] empty orders in a day; the API returned 201 for all of them; no errors in Application Insights; the partner insisted they were sending lines.
Investigation
Enabled HTTP request logging with body capture on a staging slot and replayed the partner's payload: lines were sent as `order_lines` and SKU as `sku_code`. System.Text.Json ignored the unknown names, `Lines` defaulted to an empty list, and validation didn't require at least one line.
Resolution
Cancelled and re-requested the empty orders with the partner. Added `required` and a minimum count on `Lines`, enabled `JsonUnmappedMemberHandling.Disallow` on the v2 endpoint, and gave the partner a client generated from the OpenAPI document.
Prevention
Contract tests with each partner's sample payloads in CI; a monitor alerting on orders with zero lines; onboarding checklist requiring partners to use the generated client or validate against the OpenAPI schema.

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.

↩ Usually asked after

More in Request Handling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me