A JSON field that is sometimes a number and sometimes a string looks harmless until it reaches an ASP.NET Core boundary. Model it as object, and every consumer can send almost anything. Model it as two unrelated DTOs, and the endpoint contract becomes awkward. C# 15 union API contracts give the value one name and a fixed set of cases, but the JSON wire format still needs deliberate design.
This guide uses C# 15 union API contracts in .NET 11 to preserve an existing discriminator-free format, then verifies the object read path with a runnable Dog/Cat API. Its 23 HTTP and OpenAPI assertions passed locally and on a Windows laptop. The result exposes a useful boundary: an object can match the generated anyOf alternatives while deserialization rejects it as ambiguous.
Table of Contents
Start C# 15 union API contracts with the wire format
Suppose an availability policy already uses the Kubernetes-style convention of accepting either an absolute count or a percentage. The valid JSON values are 2 and "25%". A Boolean, object, or arbitrary array must fail. That is a wire-level rule, not a presentation detail.
object cannot express that rule. It moves validation into late runtime branches and makes generated API descriptions vague. A native union puts the alternatives in the signature while preserving the existing JSON shapes: the active case is written directly, without an envelope or $type discriminator.
public union IntOrString(int, string);
IntOrString absolute = 2;
IntOrString percentage = "25%";
This is a good fit only when the two representations are intentional. If a string such as "2" is merely accidental input for a numeric field, fix the producer or reject it. A union should describe a real contract, not preserve data drift.
Declare a fixed union and handle every case
A union has a closed list of case types. Pattern matching works with those types, and the compiler can check an exhaustive switch. That changes contract evolution from a silent runtime surprise into a build-time signal.
static string Describe(IntOrString value) => value switch
{
int count when count >= 0 => $"{count} instances",
int => throw new ArgumentOutOfRangeException(
nameof(value),
"An absolute value cannot be negative."),
string percentage => ParsePercentage(percentage),
};
static string ParsePercentage(string value)
{
if (!value.EndsWith('%') ||
!int.TryParse(value[..^1], out var amount) ||
amount is < 0 or > 100)
{
throw new ArgumentException(
"A percentage must be between 0% and 100%.",
nameof(value));
}
return $"{amount}%";
}
The first layer decides which representation is active. The guards then enforce business rules inside each representation. These concerns should remain separate: the union prevents an unsupported type, while application validation rejects a supported type carrying an invalid value.
If a third case is later added and the switch is not updated, the compiler reports CS8509. Treat that warning as an error in CI for contract-owning projects. It forces every handler to acknowledge the new case before the change ships.
Separate unambiguous JSON from ambiguous JSON
Writing a union is straightforward because the runtime already knows the active case. Reading is harder: System.Text.Json must choose a case from the incoming token. A Boolean and a string are naturally distinct JSON token types. Two records are both objects, so their opening token is identical.
[JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]
public union Pet(Dog, Cat);
The structural classifier examines property names to distinguish object cases; the complete Dog and Cat definitions appear in the runnable API below. That preserves a discriminator-free format, but classification work grows with the payload and property changes can affect which case is chosen. The overlapping and missing-property fixtures later in this guide make those boundaries observable.
Web JSON options add another edge case. ASP.NET Core can read numbers from JSON strings, so an input union of int and string may require explicit custom classification even though the JSON token is a string. Output-only endpoints do not have that read-path ambiguity. Decide whether the union crosses an input boundary before calling the contract complete.
Choose a union, closed hierarchy, or open hierarchy
Use a union when alternatives are unrelated types, include primitives, or must preserve an established discriminator-free shape. Use a closed hierarchy when you own related object types and can add a discriminator. Keep a hierarchy open only when other assemblies are expected to extend it.
[JsonPolymorphic(InferClosedTypePolymorphism = true)]
public closed record class PaymentEvent(string PaymentId);
public sealed record class PaymentAuthorized(
string PaymentId,
decimal Amount) : PaymentEvent(PaymentId);
public sealed record class PaymentFailed(
string PaymentId,
string Reason) : PaymentEvent(PaymentId);
The closed hierarchy keeps shared behavior and tells C# that the known derived types form a complete set. With inferred closed-type polymorphism enabled, JSON includes a discriminator such as "$type":"PaymentAuthorized". That is usually the safer choice for a new object contract because the payload identifies its own case.
The tradeoff is compatibility. Adding a discriminator changes an existing wire format. Conversely, keeping object cases discriminator-free makes structural ambiguity your responsibility. Write the JSON contract down first, then select the C# model that matches it.
Expose the contract through ASP.NET Core
Minimal APIs can use unions in request bodies and return values. Runtime request-delegate creation and the source-generated Request Delegate Generator follow the same behavior. Keep binding at a JSON body boundary; route values, query strings, headers, and form fields do not use the union converter.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
var app = builder.Build();
app.MapOpenApi();
app.MapGet(
"/deployments/{name}/max-unavailable",
(string name) =>
TypedResults.Ok(DeploymentPolicies.Get(name)));
app.MapPost(
"/flags",
(BoolOrString flag) => TypedResults.Ok(flag));
app.Run();
public union BoolOrString(bool, string);
The return type of DeploymentPolicies.Get should be IntOrString. The separate BoolOrString request demonstrates an unambiguous read path because Boolean and string tokens differ. Avoid presenting the int|string example as a safe request body until its string-number behavior has an explicit classifier and tests.
SignalR supports unions only when it uses JsonHubProtocol; MessagePack and Newtonsoft.Json hub protocols do not. In Blazor, direct in-process component parameters require no serialization, while JavaScript interop, persisted component state, and prerendered parameters follow the same System.Text.Json rules. Inventory every serialization boundary, not merely HTTP endpoints.
Run the object-union proof
Get the runnable demo and verification runner on GitHub.
The executable reproduction uses two object cases rather than an input int|string union. A Dog has name and breed; a Cat has name and lives. This makes the property-name boundary visible without introducing a custom primitive classifier.
The recorded SDK is 11.0.100-rc.1.26425.128, with Microsoft.AspNetCore.OpenApi pinned to 11.0.0-rc.1.26425.128. Enable preview language features in a Web SDK project targeting net11.0:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi"
Version="11.0.0-rc.1.26425.128" />
</ItemGroup>
</Project>
These versions identify the reproduction, not a recommendation to deploy preview software in production. Keep the recorded SDK while reproducing the result, then rerun the fixtures when moving to another release.
The following is the API portion of the tested project. Its browser page and verification runner are omitted here; neither is needed to understand the request binding. The response header exposes the actual case selected by System.Text.Json, which is more useful than inferring it from the echoed fields.
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
builder.Services.Configure<RouteHandlerOptions>(
options => options.ThrowOnBadRequest = false);
var app = builder.Build();
app.MapOpenApi();
app.MapGet("/pets/dog", () => new Pet(new Dog("Rex", "Husky")));
app.MapGet("/pets/cat", () => new Pet(new Cat("Milo", 9)));
app.MapPost("/pets/echo", ([FromBody] Pet pet, HttpContext context) =>
{
context.Response.Headers["X-Union-Case"] = pet switch
{
Dog => "Dog",
Cat => "Cat",
null => throw new BadHttpRequestException("A pet cannot be null.")
};
return pet;
});
app.Run();
[JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]
public union Pet(Dog, Cat);
public sealed record Dog(
[property: JsonRequired] string Name,
[property: JsonRequired] string Breed);
public sealed record Cat(
[property: JsonRequired] string Name,
[property: JsonRequired] int Lives);
[JsonRequired] makes missing properties a deserialization failure. It does not replace business validation for names or acceptable values of Lives. The explicit null arm rejects a null union body, while ThrowOnBadRequest = false keeps bad binding observable as HTTP 400 in the demonstration.
The project was verified locally on Ubuntu and through the supplied PowerShell script on a Windows laptop. The Windows screenshots show the selected SDK, successful restore/build, ALL CHECKS PASSED (23), and VERIFICATION COMPLETE. They also show the live browser exchanges below; no generated-client or performance result is claimed.

The distinction between schema validation and case selection becomes clear with this request:
{"name":"Shared","breed":"Husky","lives":9}
It contains the required fields for both object cases. The generated schemas permit additional properties, so the payload can satisfy both alternatives under anyOf. The structural classifier still has to choose a single case; the mixed object is ambiguous and the API returns HTTP 400.

Changing the document to oneOf by hand would describe an exclusivity rule, but it would not change deserialization. Likewise, requiring fields does not eliminate every overlap: this mixed object contains all of them. Keep an explicit rejection fixture for the overlap, and review property additions and renames as contract changes.
| Input to POST /pets/echo | Observed result |
|---|---|
{"name":"Rex","breed":"Husky"} | HTTP 200; Dog; identical case JSON |
{"name":"Milo","lives":9} | HTTP 200; Cat; identical case JSON |
{"name":"Milo","lives":"9"} | HTTP 200; Cat; response writes numeric 9 |
| Name without a case field, or breed without name | HTTP 400 |
| Name, breed, and lives together | HTTP 400; ambiguous object |
| Numeric breed, Boolean body, or null body | HTTP 400 |
The numeric-string fixture is deliberate. Web JSON settings accept "9" for the integer property and normalize it to 9 on output. The generated lives schema therefore includes integer and string, with a numeric-string pattern. Sharing the same generated schema does not mean input and output have equally narrow representations.
Verify JSON and OpenAPI in CI
The proof runner starts the application on an available loopback port, sends real HTTP requests, fetches /openapi/v1.json, and shuts the application down. It checks the selected case header and exact response JSON for both canonical cases, the numeric-string normalization, rejection fixtures, and generated request/response schemas. This exercises the application’s web JSON settings rather than substituting default serializer options.
From the complete demo’s project folder, use these portable commands:
dotnet restore UnionProof.csproj
dotnet build UnionProof.csproj -c Release --no-restore
dotnet bin/Release/net11.0/UnionProof.dll --verify
The final command is implemented by the complete demo’s verification runner; it is not a built-in switch on a generic ASP.NET Core application. A failing check returns a nonzero exit code. On success, the runner writes the actual document to artifacts/openapi.json, the HTTP cases to artifacts/http-cases.txt, and a result record to artifacts/result.json.
For Windows, Verify-Union.ps1 performs restore, build, and the same verification, and records a transcript. Unblock the downloaded script once before running it:
Unblock-File .\Verify-Union.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\Verify-Union.ps1

The document checks require exactly the Dog and Cat standalone component references for the two GET responses and the POST request and response. They also check the required properties and absence of an added discriminator. These are bounded assertions for this contract; they do not prove that every payload admitted by the schema can be classified at runtime.
Keep the OpenAPI result as a build artifact or compare it with an approved baseline. For generated clients, regenerate and compile the actual client your consumers use, then send these fixtures through it. That additional compatibility check remains your rollout work: the 23 assertions do not include a client generator. For environment-dependent generation, use a deliberate OpenAPI host-environment policy so contract diffs are meaningful.
Roll out without surprising clients
- Freeze representative JSON fixtures before replacing an existing wrapper or
objectmodel. - Generate the OpenAPI document before and after the change and review
anyOfcase order, nullability, and component references. - Regenerate one supported client and compile its contract tests.
- Deploy an output-only union first when the input classifier is not settled.
- Track deserialization failures by endpoint without logging sensitive payloads.
Rollback should restore the previous API model and OpenAPI baseline together. Reverting only server code while leaving regenerated clients or a published schema behind creates a split contract. If a new union case is necessary, treat it as a versioned compatibility decision: exhaustive server switches will warn, but external clients do not receive that compiler protection.
C# 15 union API contracts remove a great deal of wrapper code, yet they do not remove contract design. The production-safe sequence is simple: define the JSON shapes, make ambiguous reads explicit, verify anyOf with the clients you support, and let exhaustive matching stop unhandled cases at build time.
References
- Microsoft .NET Blog: Use C# unions and closed hierarchies in ASP.NET Core
- .NET 11 RC1 C# release notes
- .NET 11 RC1 ASP.NET Core release notes
- Microsoft Learn: C# union types
- OpenAPI Specification 3.1: Schema Object
- JSON Schema: anyOf and oneOf combinations
Found this useful? Support more practical developer content.