In an ASP.NET Core 10 API, how do you send and accept enum values as names such as "Zpl" instead of numbers?
answer
- numbers by default
- JsonStringEnumConverter in Converters
- naming policy is separate from property policy
- allowIntegerValues defaults to true
- [JsonStringEnumMemberName] since .NET 9
basics
~10 sEnums serialize as numbers by default. Add JsonStringEnumConverter to the JSON options of each stack, or put [JsonConverter(typeof(JsonStringEnumConverter<LabelFormat>))] on the enum; pass a naming policy for camelCase names and allowIntegerValues: false to reject numbers.
solid answer
~40 sThe web preset leaves enums numeric, so `LabelFormat.Zpl` is written as `1`. Register `JsonStringEnumConverter` in `AddJsonOptions` for controllers and in `ConfigureHttpJsonOptions` for Minimal APIs, or annotate the enum type with `[JsonConverter(typeof(JsonStringEnumConverter<LabelFormat>))]`, which works everywhere the type is serialized. The converter writes member names as declared: the app's `PropertyNamingPolicy` does not apply to enum values, so pass `new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)` if you want `zpl`. By default it still accepts integers on input (`allowIntegerValues` is `true`); pass `false` to make names the only contract. Since .NET 9, `[JsonStringEnumMemberName("zpl-203dpi")]` renames a single member. In ASP.NET Core 10, request JSON is read through a `PipeReader`, so a hand-written converter must handle `Utf8JsonReader.HasValueSequence`.
code
csharp · 16 linesusing System.Text.Json;
using System.Text.Json.Serialization;
[JsonConverter(typeof(JsonStringEnumConverter<LabelFormat>))]
public enum LabelFormat
{
Pdf,
[JsonStringEnumMemberName("zpl-203dpi")] Zpl,
Png
}
// or app-wide, camelCase names, numbers rejected:
// builder.Services.AddControllers().AddJsonOptions(o =>
// o.JsonSerializerOptions.Converters.Add(
// new JsonStringEnumConverter(JsonNamingPolicy.CamelCase,
// allowIntegerValues: false)));go deeper
Recall that enums are numbers by default and that JsonStringEnumConverter turns them into names.
Explain the registration scopes, why the value naming policy is separate, and that allowIntegerValues defaults to true.
Plan the migration from numbers to names without breaking clients, and check hand-written converters for HasValueSequence before an upgrade to 10.
Set a house rule for enum contracts (names, casing, strictness) so every service exposes the same shape to partners.
## The default: enums are numbers ASP.NET Core's JSON options start from `JsonSerializerDefaults.Web`, which changes property naming, case-insensitive matching and quoted numbers, but **not enums**. In a shipping-label API: ```csharp public enum LabelFormat { Pdf, Zpl, Png } ``` A label with `Format = LabelFormat.Zpl` is written as `"format": 1`. Numbers are fragile: reordering members or inserting one in the middle silently changes the contract, and a client reading `1` has to know the C# declaration order. ## Three ways to switch to names | Approach | Scope | Notes | |---|---|---| | `o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter())` in `AddJsonOptions` | every enum in controller bodies | Minimal APIs need the same line in `ConfigureHttpJsonOptions` (`o.SerializerOptions`) | | `[JsonConverter(typeof(JsonStringEnumConverter<LabelFormat>))]` on the enum | that enum, everywhere it is serialized | travels with the type into both stacks and into `HttpClient` code; the generic form is the AOT-friendly one | | `[JsonConverter(typeof(JsonStringEnumConverter))]` on one property | that property | useful when only one contract needs names | ## Naming and strictness The converter has two constructor arguments, `namingPolicy` and `allowIntegerValues`: - **Names are written as declared.** The app-wide `PropertyNamingPolicy` (camelCase) applies to property names, **not** enum values, so the default output is `"Zpl"`. Pass `new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)` for `"zpl"`, or `JsonNamingPolicy.SnakeCaseLower` for multi-word members. - **Integers are still accepted** on input because `allowIntegerValues` defaults to `true`. A client that sends `1` keeps working, which helps a migration but leaves two contracts alive. Pass `allowIntegerValues: false` once clients have moved. - **One member, one custom name:** since .NET 9, `[JsonStringEnumMemberName("zpl-203dpi")]` on an enum field overrides the name for that member only, in both directions. ## What clients and documentation see 1. Responses now carry stable names that survive reordering of the enum. 2. Requests with an unknown name fail to bind; in an `[ApiController]`, the formatter's error lands in `ModelState` and the client gets a 400. 3. The built-in OpenAPI document (`Microsoft.AspNetCore.OpenApi`) builds its schemas from the Minimal API `JsonOptions`. A converter registered only through `AddJsonOptions` therefore does not reach it, while `[JsonConverter]` on the enum type does, and the schema then lists the string values. ## A .NET 10 trap for hand-written converters Teams that outgrow the built-in converter sometimes write a `JsonConverter<LabelFormat>` that reads `reader.ValueSpan`. In ASP.NET Core 10, MVC, Minimal APIs and `ReadFromJsonAsync` deserialize request bodies through a **`PipeReader`** instead of a `Stream`. A token can then span several buffer segments, `Utf8JsonReader.HasValueSequence` is `true`, and `ValueSpan` does not hold the token. The release notes name missing data and errors such as `ArgumentOutOfRangeException` as the result. The fix is to read `reader.ValueSequence` when `HasValueSequence` is set. As a temporary measure, the `Microsoft.AspNetCore.UseStreamBasedJsonParsing` AppContext switch restores the stream-based path. ## Moving a live API from numbers to names Changing the wire format of an enum is a contract change, so do it in steps: 1. Register the converter with `allowIntegerValues` left at `true`. Responses switch to names, and old clients that still send numbers keep working. 2. Publish the new schema and tell clients that numeric input is deprecated. 3. Watch request logs or metrics for numeric enum input until it stops. 4. Switch to `allowIntegerValues: false`, so only names are accepted. Clients that read responses must handle names from step 1 on, so coordinate that step with the consumers that parse the `format` field. ## Interview checklist - Enums are numeric under the web defaults. - The converter has to be registered for each stack, or placed on the type. - Naming policy for values is separate from property naming. - `allowIntegerValues` defaults to `true`. - Custom converters must handle `HasValueSequence` on .NET 10.
- After moving to .NET 10, a custom JsonConverter for tracking numbers loses characters on large request bodies. What changed?ASP.NET Core 10 reads request JSON through a `PipeReader`, so a token can span buffer segments. When `Utf8JsonReader.HasValueSequence` is `true`, `ValueSpan` does not hold the token; the converter must read `ValueSequence`. The `Microsoft.AspNetCore.UseStreamBasedJsonParsing` AppContext switch is a temporary way back while the converter is fixed.
- Why is putting the converter attribute on the enum type often better than registering it in options?`[JsonConverter(typeof(JsonStringEnumConverter<LabelFormat>))]` travels with the type, so controllers, Minimal APIs and `HttpClient` code all write names without each remembering to register the converter. The generic form also suits trimming and Native AOT, where the non-generic factory is less friendly.
- ASP.NET Core's web defaults already write enums as their names.
- JsonStringEnumConverter follows PropertyNamingPolicy, so enum values become camelCase automatically.
- Once JsonStringEnumConverter is registered, numeric enum values are rejected by default.
- Adding the converter in AddJsonOptions also covers Minimal API endpoints.
- A custom converter can always rely on ValueSpan when reading request JSON in .NET 10.
Assumes ASP.NET Core 10: JsonStringEnumMemberNameAttribute exists since .NET 9, and request JSON is read through a PipeReader since 10.