Development Playbook

Your agent's API accepts payloads it should reject: pin the JSON contract with a rejection corpus and .NET 10 strict options

Eight bad request bodies, one xUnit theory and seven System.Text.Json settings. The corpus fails nine of ten checks on a default ASP.NET Core API, and gives the agent a target to harden against. About 15 minutes to try.

A steel turnstile gate in a dark concrete wall with a stream of envelopes queuing in front and only one passing through, lit in pink halftone

A client sends {"email":"a@b.c","age":30,"rol":"Admin"}. The API answers 201 Created with a viewer account, because rol isn’t a property it knows and nobody told it to care. Another client sends "amount":10 and then, further down the same object, "amount":9999. The API charges 9999. A third omits email entirely and gets an account with a null address.

None of those are exotic. They’re what a default ASP.NET Core minimal API does with a record an agent wrote in thirty seconds, and the agent’s own tests won’t notice, because the agent’s tests send the payloads the agent had in mind. The defects live in the payloads nobody wrote.

The fix has two halves. A small corpus of bad request bodies that must all come back as 400, written before the options are touched. Then a handful of System.Text.Json settings, most of them new or newly bundled in .NET 10, until the corpus is green. Run it and you have a wire contract that fails loudly when an agent (or a person) loosens it. Everything here runs on the .NET 10 SDK and works with any coding agent that can read files and run dotnet test.

The API under test

Two endpoints and three types is enough. This is the shape of thing an agent produces from “add a create-user endpoint and a transfer endpoint”:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapPost("/users", (CreateUser body) => Results.Created($"/users/{body.Email}", body));
app.MapPost("/transfers", (Transfer body) => Results.Ok(body));
app.Run();

public enum Role { Viewer, Editor, Admin }
public record CreateUser(string Email, int Age, Role Role = Role.Viewer);
public record Transfer(string Account, decimal Amount);
public partial class Program;

The last line makes the entry point visible to the test host. The project is the stock dotnet new web template for net10.0 with nullable reference types on, which matters later.

Nothing in this is wrong as code. It compiles, the happy path works, and a reviewer reading the diff has no reason to stop. The problem is what the framework does with input that doesn’t match, and that behaviour is configured by defaults rather than by anything in the diff.

Write the rejection corpus first

One xUnit theory, one row per way a payload can be wrong. Each row is a name, a path and a body, and the assertion is a 400.

using System.Net;
using System.Text;
using Microsoft.AspNetCore.Mvc.Testing;

public class WireContractTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>>
{
    public static TheoryData<string, string, string> Rejected => new()
    {
        { "unknown property (typo)",   "/users",     """{"email":"a@b.c","age":30,"rol":"Admin"}""" },
        { "duplicate property",        "/transfers", """{"account":"A-1","amount":10,"amount":9999}""" },
        { "missing required property", "/users",     """{"age":30}""" },
        { "null for non-nullable",     "/users",     """{"email":null,"age":30}""" },
        { "enum number out of range",  "/users",     """{"email":"a@b.c","age":30,"role":99}""" },
        { "enum number in range",      "/users",     """{"email":"a@b.c","age":30,"role":2}""" },
        { "number as string",          "/transfers", """{"account":"A-1","amount":"10"}""" },
        { "wrong property case",       "/transfers", """{"ACCOUNT":"A-1","Amount":10}""" },
    };

    [Theory, MemberData(nameof(Rejected))]
    public async Task Bad_payload_is_rejected_with_400(string name, string path, string json)
    {
        var client = factory.CreateClient();
        var res = await client.PostAsync(path, new StringContent(json, Encoding.UTF8, "application/json"));
        Assert.True(res.StatusCode == HttpStatusCode.BadRequest,
            $"{name}: expected 400 but got {(int)res.StatusCode}");
    }

    [Fact]
    public async Task Valid_payload_is_accepted()
    {
        var client = factory.CreateClient();
        var res = await client.PostAsync("/users",
            new StringContent("""{"email":"a@b.c","age":30,"role":"Editor"}""", Encoding.UTF8, "application/json"));
        Assert.Equal(HttpStatusCode.Created, res.StatusCode);
    }
}

The Valid_payload_is_accepted test is the guard against over-correcting. A contract that rejects everything passes the first theory, so one known-good body has to stay green. The message string carries the row name so a failure says which defect got through, not just that a theory case failed.

The project needs xunit 2.9.x and Microsoft.AspNetCore.Mvc.Testing. Pin that package to 10.0.*: the newest release on the feed targets net11.0 and refuses to restore into a net10.0 project, with an NU1202 error.

Watch it fail

Run dotnet test against the unhardened API and the output is the argument for the whole exercise:

  Failed WireContractTests.Bad_payload_is_rejected_with_400(name: "wrong property case", ...)
   wrong property case: expected 400 but got 200
  Failed WireContractTests.Bad_payload_is_rejected_with_400(name: "missing required property", ...)
   missing required property: expected 400 but got 201
  Failed WireContractTests.Bad_payload_is_rejected_with_400(name: "enum number out of range", ...)
   enum number out of range: expected 400 but got 201
  Failed WireContractTests.Bad_payload_is_rejected_with_400(name: "null for non-nullable", ...)
   null for non-nullable: expected 400 but got 201
  Failed WireContractTests.Bad_payload_is_rejected_with_400(name: "number as string", ...)
   number as string: expected 400 but got 200
  Failed WireContractTests.Bad_payload_is_rejected_with_400(name: "unknown property (typo)", ...)
   unknown property (typo): expected 400 but got 201
  Failed WireContractTests.Bad_payload_is_rejected_with_400(name: "duplicate property", ...)
   duplicate property: expected 400 but got 200
  Failed WireContractTests.Bad_payload_is_rejected_with_400(name: "enum number in range", ...)
   enum number in range: expected 400 but got 201
  Failed WireContractTests.Valid_payload_is_accepted
Failed!  - Failed:     9, Passed:     1, Skipped:     0, Total:    10, Duration: 432 ms

Nine failures out of ten. Eight are the corpus. The ninth is the known-good body: the default options don’t read "Editor" as a Role at all, because enums travel as numbers unless a converter says otherwise. An agent that writes API docs showing string enums, and a test that sends numbers, produces a service whose documentation doesn’t work.

The in-range number is on the list on purpose. "role":2 is Admin. A client that sends a bare integer is coupled to the declaration order of an enum, so inserting Auditor between Editor and Admin silently promotes every client that sent 2.

Harden the options

The settings go in ConfigureHttpJsonOptions, which is what minimal APIs read when they bind a body. ASP.NET Core starts that object from the web defaults (camel case, case-insensitive property names, numbers allowed as strings), so each loosening has to be undone explicitly:

builder.Services.ConfigureHttpJsonOptions(o =>
{
    var j = o.SerializerOptions;
    j.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow;
    j.AllowDuplicateProperties = false;
    j.PropertyNameCaseInsensitive = false;
    j.RespectNullableAnnotations = true;
    j.RespectRequiredConstructorParameters = true;
    j.NumberHandling = JsonNumberHandling.Strict;
    j.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: false));
});

Add using System.Text.Json; and using System.Text.Json.Serialization; at the top of Program.cs. Run the tests again:

Passed!  - Failed:     0, Passed:    10, Skipped:     0, Total:    10, Duration: 363 ms

That’s the whole change: seven lines and no endpoint code touched. Here’s what each one buys.

UnmappedMemberHandling = Disallow turns the rol typo into a 400. It’s been available since .NET 8, per the Microsoft docs on unmapped members , which also describe a per-type attribute and a contract-level hook.

AllowDuplicateProperties = false is new in .NET 10. The .NET 10 libraries notes say the JSON specification doesn’t define how duplicates are handled and that this “can lead to unexpected results and security vulnerabilities”. With the default, the last value wins, which is why the transfer above charges 9999. The security angle is the usual one for parser disagreement: if a gateway, a validator or a log line reads the first amount and the handler reads the last, they’ve approved different requests.

PropertyNameCaseInsensitive = false makes ACCOUNT a mismatch instead of a quiet match. A client that sends ACCOUNT is usually following some other convention, and it’s better to find out at the boundary.

RespectNullableAnnotations makes null for a string (not string?) a 400 instead of a null that surfaces three layers down. It only does anything if the project has <Nullable>enable</Nullable>, which the web template sets.

RespectRequiredConstructorParameters makes a constructor parameter with no default value required in the payload. Without it the missing email becomes a null, and that’s the quieter of the two outcomes; more on the louder one below.

NumberHandling = Strict undoes the web default that lets "10" bind as a number. A client that sends a quoted number is usually a client that formats currency as text somewhere, and it’s better to find that out at the boundary.

JsonStringEnumConverter(allowIntegerValues: false) fixes both enum rows and the valid-payload row at once: names in, names out, numbers refused.

Check that every line earns its place

Agents tidy. A setting that nothing visibly depends on is a candidate for deletion in a later “cleanup” diff, and the corpus is what stops that. To confirm the corpus is actually covering each line, remove them one at a time and rerun:

== without UnmappedMemberHandling
   unknown property (typo): expected 400 but got 201
== without AllowDuplicateProperties
   duplicate property: expected 400 but got 200
== without PropertyNameCaseInsensitive
   wrong property case: expected 400 but got 200
== without RespectNullableAnnotations
   null for non-nullable: expected 400 but got 201
== without RespectRequiredConstructorParameters
   missing required property: expected 400 but got 500
== without NumberHandling
   number as string: expected 400 but got 200
== without JsonStringEnumConverter
   enum number out of range: expected 400 but got 201
   enum number in range: expected 400 but got 201

Each removal fails exactly the test for the defect it guards (the last one also fails the valid-payload test, not shown). Seven settings, seven independent failures, so none is redundant.

The surprise is the fifth line. With every other setting in place but RespectRequiredConstructorParameters removed, a missing email doesn’t produce a quiet null. It produced a 500, in a configuration where nullable annotations were enforced and required parameters weren’t. The cause wasn’t chased further. A 500 on bad client input is worse than either a 400 or a null: it pages someone, and it hides in error-rate dashboards as a server fault.

The preset, and where it stops

.NET 10 also ships JsonSerializerOptions.Strict, a preset that bundles most of this. Per the docs it disallows unmapped members, disables duplicate properties, keeps property binding case-sensitive, and turns on both RespectNullableAnnotations and RespectRequiredConstructorParameters. Reading its properties back confirms it, and also shows NumberHandling as Strict.

Two limits. First, it’s a ready-made options instance, not something to assign to ASP.NET’s options object, so the HTTP binding path above still sets the properties one by one. The preset is the right tool for the other places JSON gets parsed: a message from a queue, a config file, a cached blob, a webhook payload deserialized by hand.

var cmd = JsonSerializer.Deserialize<CreateUser>(message, JsonSerializerOptions.Strict);

Second, it carries no enum converter, and it keeps PropertyNamingPolicy unset, so it reads PascalCase names. Feed it the valid {"email":...,"role":"Admin"} body and it throws, because it can’t turn the string Admin into a Role. Copy it with new JsonSerializerOptions(JsonSerializerOptions.Strict) { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Converters = { new JsonStringEnumConverter(allowIntegerValues: false) } } when the wire format is camel-cased with named enums.

Make the agent keep it

The corpus is only useful if the agent has to satisfy it. A prompt that works in any agent:

Add the endpoint described below. Before writing any handler code, add
a row to Rejected in WireContractTests for each way its payload can be
wrong: unknown property, duplicate property, missing required property,
null for a non-nullable property, wrong enum value, wrong JSON type,
wrong property case. Run dotnet test and show me the rows failing for
the right reason. Then implement. Do not edit ConfigureHttpJsonOptions
to make a row pass; if a row can't pass without a settings change, stop
and tell me which setting and why.

The last instruction matters. The cheapest way to get a failing row green is to relax a setting, and an agent under a “make the tests pass” instruction will find that route. Pairing the corpus with a rule that the options are the contract, not a knob, keeps the diff reviewable. If the repo has a CODEOWNERS file, point the ConfigureHttpJsonOptions block at a human.

A cheap addition for response-heavy APIs: add the same kind of test in the other direction, asserting that responses don’t contain null for fields the schema declares non-nullable. That’s a separate defect, and the contract-first post covers one instance of it.

Make it yours

For an endpoint that must be liberal in what it accepts, a webhook from a vendor who adds fields without notice, relax one type rather than the whole API. The documented attribute does it per type:

[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Skip)]
public record VendorEvent(string Id, string Kind);

Keep the duplicate and nullability rules for that type. Only the unknown-field rule is a compatibility decision.

For a public API with clients you don’t control, think about rollout before turning on Disallow. A client that sends an extra field today gets a 200 now and a 400 after the change. Log the unmapped properties for a release, count them, and flip to rejection once the count is zero or the affected clients have been told. The same applies to case sensitivity: a client that has been sending Account against a camel-case API for two years has been relying on the leniency.

If the service uses source-generated serialization, that path wasn’t run here. Point the same corpus at it before trusting it.

What goes wrong

Rejecting unknown fields breaks forward compatibility. If a newer client adds a field before the server knows it, the old server now refuses the request that the lenient one would have served. That’s the right trade for a first-party API deployed together and a poor one for anything with independent release trains.

The corpus covers shape, not meaning. Nothing in these options rejects "age":-5 or an email that isn’t one. Range and format rules belong in a validation layer, and the AddValidation post covers that side. The two are complementary: the JSON options decide what counts as a parseable request, validation decides whether a parsed one is acceptable.

The 400 body is whatever the framework emits, and this corpus doesn’t look at it. If clients parse error responses, pin the body in a separate test.

And don’t bother if the service only accepts payloads from code you generate from the same types on both ends. The drift this prevents comes from clients you don’t control, or from an agent that edits one side.

First 15 minutes

Run dotnet new web -n Api -f net10.0 and dotnet new xunit -n Api.Tests -f net10.0, reference the API from the tests, add Microsoft.AspNetCore.Mvc.Testing at 10.0.*, and paste in the test class above. Run dotnet test and watch nine tests fail. Then paste the seven-line options block and watch them go green.

On a real service, skip the sample and point the corpus at one existing endpoint. Add only the rows that make sense for its payload, run it, and count how many pass without a code change.