10.5 — Content Negotiation and JSON Serialization¶
← Roadmap · Section: 10. Web API Design and REST Prev: 10.4
[ApiController]· Next: 10.6 API versioning
Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Content negotiation is the client saying what format it wants via the Accept header, and the
server picking a formatter that can produce it.
- ASP.NET Core ships JSON only. XML is opt-in, so
Accept: application/xmlstill gets JSON unless you add the formatter. System.Text.Jsonis the default — fast, allocation-light, and strict.Newtonsoft.Jsonis lenient and full-featured.- The defaults that bite: camelCase output, case-insensitive input, and no support for trailing commas or comments.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Content negotiation | a mechanism | The client requests a format; the server picks a formatter. |
Accept |
a request header | What formats the client can handle. |
Content-Type |
a header | What format this message body actually is. |
| Output formatter | a class | Turns your object into a response body. |
| Input formatter | a class | Turns a request body into your object. |
System.Text.Json |
the built-in serializer | Fast, strict, span-based. The default since .NET Core 3.0. |
Newtonsoft.Json |
a NuGet package | The older serializer. Lenient, more features, slower. |
JsonSerializerOptions |
a class | Naming policy, casing, null handling, converters. |
JsonConverter<T> |
an abstract class | Custom read/write logic for one type. |
[JsonPropertyName] |
an attribute | Renames a property in JSON. |
[JsonIgnore] |
an attribute | Leaves a property out of the JSON. |
[Produces] |
an attribute | Restricts what an action can return. |
[Consumes] |
an attribute | Restricts what an action accepts. |
| 406 Not Acceptable | a status code | No formatter can produce what the client asked for. |
| 415 Unsupported Media Type | a status code | The request body's Content-Type cannot be read. |
The concept¶
The same resource can be represented in several formats. An order is not JSON — JSON is one representation of it (10.1).
Content negotiation is how the client and server agree which one:
The server looks at Accept, finds a formatter that can produce application/json, and uses it.
⚠️ The catch: out of the box, ASP.NET Core has exactly one formatter, and it produces JSON.
GET /api/orders/42
Accept: application/xml
→ 200 OK
Content-Type: application/json ⚠️ not what was asked for
By default, an unsatisfiable Accept header gets the default formatter anyway rather than a
406. Whether that is helpful or dishonest is a fair debate, but it is the behaviour, and it is a
common "why is my XML client getting JSON?" bug.
To make it return 406 instead:
Accept vs Content-Type¶
Constantly confused, and the distinction is simple:
Accept— a request header. "Here is what I can read."Content-Type— on either message. "Here is what this body is."
POST /api/orders
Content-Type: application/json ← what I am SENDING
Accept: application/json ← what I want BACK
Get the wrong one and you get 415 (server cannot read your body) rather than 406 (server cannot produce your format).
How it works¶
The two serializers¶
System.Text.Json |
Newtonsoft.Json |
|
|---|---|---|
| Default since | .NET Core 3.0 | Was default before |
| Speed | ✅ ~2x faster | Slower |
| Allocations | ✅ Much lower | Higher |
| Strictness | ⚠️ Strict | Lenient |
| Trailing commas | ❌ By default | ✅ |
| Comments in JSON | ❌ By default | ✅ |
Quoted numbers ("5" → int) |
❌ By default | ✅ |
DataTable, dynamic |
⚠️ Limited | ✅ |
| Polymorphic serialization | ✅ .NET 7+ via [JsonDerivedType] |
✅ Long-standing |
JsonPatchDocument |
❌ | ✅ Required |
| Circular references | ✅ ReferenceHandler.Preserve |
✅ |
The strictness is the migration pain. Code that worked on Newtonsoft breaks because a client
was sending "quantity": "5" — a string where an int was expected — and Newtonsoft quietly coerced
it while System.Text.Json throws.
That is arguably the better behaviour. But it surfaces as production 400s on the day you migrate, so it needs to be a deliberate decision.
Switching back, if you need JSON Patch or a lenient contract:
builder.Services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
⚠️ That changes serialization for the whole application, not just the actions that need it. Every response now goes through Newtonsoft, with its different null handling, date formats and casing defaults. It is not a local decision.
The casing rules that surprise people¶
Output is camelCase. Input is case-insensitive. Those are two different defaults and both catch people out.
public class OrderDto
{
public int OrderId { get; set; } // C# PascalCase
public string CustomerName { get; set; } = "";
}
⚠️ The property is OrderId in C# and orderId in JSON. A JavaScript client reading
response.OrderId gets undefined — silently, because JavaScript does not error on a missing
property.
To keep PascalCase:
builder.Services.AddControllers().AddJsonOptions(o =>
o.JsonSerializerOptions.PropertyNamingPolicy = null); // null = leave names alone
⚠️ Meanwhile input binding is case-insensitive by default in ASP.NET Core — MVC configures
PropertyNameCaseInsensitive = true even though raw JsonSerializer.Deserialize defaults to
case-sensitive. So a client can send OrderId, orderId or ORDERID to your API and all three
bind, but the same JSON passed to JsonSerializer.Deserialize in a unit test does not. That
asymmetry produces genuinely confusing test failures.
The other defaults worth knowing¶
| Behaviour | System.Text.Json default |
|---|---|
| Nulls | Included — "phone": null appears |
| Fields (not properties) | Ignored |
| Read-only properties | Serialized, not deserialized |
| Enums | Numbers — Status = Pending → 0 |
DateTime |
ISO 8601 round-trip |
| Non-ASCII | Escaped — é → é |
| Dictionary keys | Not camelCased unless configured |
⚠️ Enums as numbers is the one that causes real friction. "status": 2 means nothing to a
client, and inserting a new enum member in the middle silently renumbers everything after it —
breaking every stored value and every client. Serialize enums as strings:
⚠️ And "phone": null on every nullable field bloats payloads. DefaultIgnoreCondition =
JsonIgnoreCondition.WhenWritingNull removes them — but check first that clients do not distinguish
"null" from "absent" (10.2).
The deeper detail — per-action control¶
[HttpGet("{id:int}")]
[Produces("application/json")] // this action only produces JSON
public ActionResult<OrderDto> Get(int id) => Ok(...);
[HttpPost]
[Consumes("application/json")] // reject anything else with 415
public IActionResult Create(CreateOrderRequest req) => Ok();
⚠️ [Produces] does more than document. It constrains the negotiation — a client asking for
XML gets 406 even if the XML formatter is registered. Useful when you mean it, surprising when you
copied it from a template.
Adding XML, when a legacy client genuinely needs it:
builder.Services.AddControllers(o => o.ReturnHttpNotAcceptable = true)
.AddXmlSerializerFormatters();
⚠️ XmlSerializer has requirements your DTOs may not meet: a public parameterless constructor,
public settable properties, and no interfaces or Dictionary<K,V>. Records with init accessors
often fail. Adding XML support to an existing API is rarely a one-liner.
Source generation and AOT¶
For high-throughput APIs or Native AOT, reflection-based serialization is the bottleneck. The source generator emits serialization code at compile time:
[JsonSerializable(typeof(OrderDto))]
[JsonSerializable(typeof(PagedResult<OrderDto>))]
internal partial class ApiJsonContext : JsonSerializerContext { }
builder.Services.ConfigureHttpJsonOptions(o =>
o.SerializerOptions.TypeInfoResolverChain.Insert(0, ApiJsonContext.Default));
Faster startup, lower allocations, and it works under trimming where reflection does not (21.10).
Code¶
A configuration block with the reasoning attached:
builder.Services
.AddControllers(options =>
{
// Honour Accept honestly: 406 rather than silently returning JSON
options.ReturnHttpNotAcceptable = true;
})
.AddJsonOptions(options =>
{
var json = options.JsonSerializerOptions;
// camelCase is the default; stated explicitly so it is a decision, not an accident
json.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
json.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase; // NOT camelCased by default
// Enums as strings. "pending" survives reordering the enum; 2 does not.
json.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
// Drop nulls — smaller payloads.
// ⚠️ Only safe if clients do not distinguish "null" from "absent".
json.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
// Tolerate trailing commas and comments from hand-written clients
json.AllowTrailingCommas = true;
json.ReadCommentHandling = JsonCommentHandling.Skip;
// ⚠️ Development only. Indented JSON is ~20% larger on the wire.
json.WriteIndented = builder.Environment.IsDevelopment();
});
A DTO showing the attributes:
public sealed record OrderDto
{
public int Id { get; init; } // → "id"
[JsonPropertyName("customer_name")] // legacy client expects snake_case
public string CustomerName { get; init; } = "";
[JsonIgnore]
public string InternalNotes { get; init; } = ""; // never leaves the server
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? CancelledReason { get; init; } // omitted unless set
public OrderStatus Status { get; init; } // → "pending" with the converter
[JsonConverter(typeof(MoneyConverter))]
public decimal Total { get; init; } // → "99.50", never 99.5000001
}
That last one matters more than it looks. decimal round-trips exactly through
System.Text.Json, but JavaScript's number is a double — so a client reading a large or
high-precision decimal loses accuracy silently. Serializing money as a string is the usual defence.
A converter for a legacy date format:
public sealed class LegacyDateConverter : JsonConverter<DateTime>
{
private const string Format = "yyyyMMdd";
public override DateTime Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions o)
=> DateTime.ParseExact(reader.GetString()!, Format, CultureInfo.InvariantCulture);
// ⚠️ InvariantCulture, always. Server culture must not change the wire format.
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions o)
=> writer.WriteStringValue(value.ToString(Format, CultureInfo.InvariantCulture));
}
Interview questions¶
Q: What is content negotiation and how does ASP.NET Core do it?
The client sends an Accept header saying what formats it can handle, and the server picks an
output formatter that can produce one of them. The thing to know is that ASP.NET Core ships with
JSON only — XML is opt-in — and by default an unsatisfiable Accept header gets the default
formatter anyway rather than a 406, which is why an XML client silently receives JSON. Setting
ReturnHttpNotAcceptable = true makes it honest and return 406 instead.
Q: What is the difference between System.Text.Json and Newtonsoft.Json?
System.Text.Json is the default since .NET Core 3.0 — roughly twice as fast, far fewer
allocations, and much stricter. Newtonsoft is lenient: it accepts trailing commas, comments and
quoted numbers, and has features System.Text.Json lacks, notably JsonPatchDocument, which is
why JSON Patch still requires the Newtonsoft package. The strictness is the migration pain — a
client sending a string where an int was expected worked on Newtonsoft and throws now. And
switching back applies to the whole application, not one action.
Q: What are the default serialization behaviours that catch people out?
Output is camelCase while your C# is PascalCase, so a JavaScript client reading response.OrderId
gets undefined silently. Input binding, meanwhile, is case-insensitive under MVC even though raw
JsonSerializer.Deserialize is case-sensitive — so the same payload behaves differently in a unit
test. And enums serialize as numbers by default, which means clients see 2, and inserting a new
enum member in the middle silently renumbers everything after it. Adding JsonStringEnumConverter
is close to a default I would apply on every project.
Q: How do you customise how one type is serialized?
A JsonConverter<T> with Read and Write overrides, registered either globally in
JsonSerializerOptions.Converters or on a specific property with [JsonConverter]. Typical cases
are a legacy date format, a value object that should be a plain string on the wire, or money —
decimal round-trips exactly in .NET but JavaScript numbers are doubles, so serializing money as a
string avoids silent precision loss. Inside the converter, always use InvariantCulture, or the
wire format changes with the server's locale.
Traps ⚠️¶
Accept: application/xmlreturns JSON unlessReturnHttpNotAcceptableis set.- XML is not registered by default.
AddXmlSerializerFormatters()is required. - camelCase output vs PascalCase C# — JS clients get
undefined, silently. - Input is case-insensitive in MVC but case-sensitive in raw
JsonSerializer. - Enums serialize as numbers, and reordering the enum renumbers the contract.
AddNewtonsoftJson()changes serialization app-wide, not per action.System.Text.Jsonrejects trailing commas, comments and quoted numbers by default.decimalbecomes a JavaScript double — precision loss on money.[Produces]constrains negotiation, not just documentation — it can cause 406s.WriteIndentedin production inflates every response.XmlSerializercannot handle records, interfaces or dictionaries without work.- Dictionary keys are not camelCased unless
DictionaryKeyPolicyis set. - 415 vs 406: 415 is your body, 406 is your
Accept.
Related¶
- 10.1 REST principles — representations vs resources
- 10.3 Status codes — 406 and 415
- 10.4
[ApiController]— it does not force JSON - 10.2 HTTP verbs — why JSON Patch needs Newtonsoft
- 10.11 DTOs and mapping — what you serialize
- 11.2 How binding works — the input side
- 21.10 Native AOT — source-generated serialization
- 21.8 Localization — culture and formatting