Return 400 for a missing enum in ASP.NET Core with required
If a request body omits an enum property, System.Text.Json does not complain: the property keeps its default value, which is the enum member with the value 0. To make an omitted enum a 400 instead of a silent wrong answer, mark the property with the C# required modifier. Since .NET 7, System.Text.Json treats required members as mandatory in JSON, throws a JsonException when one is missing, and ASP.NET Core turns that into a 400.
How an omitted enum turned into a 200 with the wrong behaviour
A .NET service I work on gained a new property on one of its request records: an enum that chose which family of prompts the service should run. Existing callers didn't send it yet, and new callers were supposed to. The endpoints all returned 200 in testing, which is exactly the problem. A caller that forgot the field got a perfectly valid response for the wrong family, because the missing property had quietly become the first enum member.
Someone had even seen this coming and ordered the enum so the omission would land on the most sensible default. That works until the next person adds a member at the top, reorders the list alphabetically, or decides the "sensible" default has changed. Member order is a terrible place to keep an API contract, because nothing about it looks like a contract.
Why System.Text.Json binds the first member
System.Text.Json fills in the properties it finds in the JSON and leaves the rest alone. An enum is a value type, so a property nobody set holds default(T), which is whatever member has the numeric value 0. With no explicit values that is the first one declared. No exception, no model state error, no log line. From the controller's point of view the caller asked for that member.
The same is true whether the enum is written as a number or, with JsonStringEnumConverter, as a string. The converter only matters when the property is present.
How to make the property mandatory with required
The fix is one keyword. The C# required modifier (C# 11) makes object initialisers set the property at compile time, and System.Text.Json on .NET 7 and later reads it as "this property must appear in the JSON":
using System.Text.Json.Serialization;
[JsonConverter(typeof(JsonStringEnumConverter<ReportKind>))]
public enum ReportKind
{
Summary,
Detailed
}
public sealed record ReportRequest
{
public required ReportKind Kind { get; init; }
public string? Notes { get; init; }
}
Now deserialising {"notes":"x"} throws a JsonException saying the type was missing required properties, and names kind. In an [ApiController], the System.Text.Json input formatter catches that exception, adds a model state error, and the automatic validation filter returns a 400 problem details response before your action runs. Minimal APIs reject the body with a 400 as well.
If you prefer positional records, required can't go on a constructor parameter. Use the attribute on the generated property instead:
public sealed record ReportRequest(
[property: JsonRequired] ReportKind Kind,
string? Notes);
One side effect to expect: every place in your own code that builds the record now has to set Kind, or it won't compile. That is the point: an internal caller that forgets the field fails at build time instead of at runtime.
What about None = 0 or a nullable enum with [Required]?
There are two older patterns, and both work if you're careful:
- A sentinel member. Add
None = 0(orUnspecified) and validate that the value isn't it. This keeps the wire format unchanged and works on any .NET version, but the sentinel leaks into every switch statement and every consumer has to remember it isn't a real option. - A nullable enum with
[Required]. Make the propertyReportKind?and add the data annotation. Model validation then reports a missing value as null. Note that[Required]on a non-nullable enum does nothing useful: the value is never null, so the check always passes.
I went with required because the contract lives on the property itself, the compiler enforces it for internal callers, and the serializer enforces it for external ones. There is no extra member to explain and no validation attribute to keep in sync.
How to test that the 400 comes from the missing field
I wrote two kinds of test. The first pins the serializer behaviour directly, so it fails if someone removes the keyword:
[Fact]
public void Deserialize_WithoutKind_Throws()
{
var act = () => JsonSerializer.Deserialize<ReportRequest>(
"""{"notes":"x"}""", JsonSerializerOptions.Web);
Assert.Throws<JsonException>(act);
}
The second goes over real HTTP with WebApplicationFactory, for every endpoint that takes the record. Each case posts the same body twice: once without the enum, expecting 400, and once with it, expecting 200. The second half matters more than it looks. Without it, a 400 could come from anything else wrong in the body, and the test would pass for the wrong reason.
[Theory]
[InlineData("/reports")]
[InlineData("/reports/preview")]
public async Task Post_RequiresKind(string path)
{
var client = _factory.CreateClient();
var missing = await client.PostAsJsonAsync(path, new { notes = "x" });
var present = await client.PostAsJsonAsync(path, new { notes = "x", kind = "Summary" });
Assert.Equal(HttpStatusCode.BadRequest, missing.StatusCode);
Assert.Equal(HttpStatusCode.OK, present.StatusCode);
}
Wire names are a separate decision
Making the property required says nothing about what values look like on the wire. If you serialise enums as strings, the member names become part of your public API, and renaming a member breaks callers. On .NET 9 and later, JsonStringEnumMemberName lets you pin the wire name separately from the C# name, so you can tidy the code without changing the contract. I'd decide both at the same time: required for presence, explicit names for spelling.
Key takeaways
- System.Text.Json leaves an omitted enum property at its default, which is the member with value 0, without any error.
- The C#
requiredmodifier makes System.Text.Json on .NET 7+ throw for a missing property, and ASP.NET Core returns that as a 400. - Use
[property: JsonRequired]when the request is a positional record. [Required]only helps on a nullable enum; on a non-nullable one it always passes.- Test the 400 and the matching 200 together, so the test proves the missing field caused the rejection.