-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
Is there an existing issue for this?
- I have searched the existing issues
Describe the bug
When a property is decorated with [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)], validation attributes (e.g., [MaxLength]) on that property are not enforced during model binding, even when the property value is present in the incoming request.
The JsonIgnoreCondition.WhenWritingDefault condition should only affect serialization (writing JSON output). It should not affect deserialization or validation of incoming requests.
Expected Behavior
A property with [MaxLength(10)] should be validated regardless of [JsonIgnore] attributes. The request should return 400 Bad Request when the value exceeds the maximum length.
Steps To Reproduce
Full repro: https://github.com/glenndierckx/aspnetcore-jsonignore-validation-bug
// Request model
public class ValidationTestRequest
{
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault), MaxLength(10)]
public string? PropertyWithJsonIgnoreWhenWritingDefault { get; set; }
[MaxLength(10)]
public string? PropertyWithoutJsonIgnore { get; set; }
}
// Endpoint
app.MapPost("/test-validation", (ValidationTestRequest _) => Results.Ok());Test Results:
| Property | JsonIgnore Attribute | Value Sent | Expected | Actual |
|---|---|---|---|---|
PropertyWithoutJsonIgnore |
None | "ExceedsMaxLength" (14 chars) |
400 Bad Request |
400 Bad Request ✅ |
PropertyWithJsonIgnoreWhenWritingDefault |
WhenWritingDefault |
"ExceedsMaxLength" (14 chars) |
400 Bad Request |
200 OK ❌ |
Exceptions (if any)
No exception is thrown. The validation is silently bypassed and the endpoint handler is invoked with invalid data.
.NET Version
10.0.100
Anything else?
No response