aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

[JsonIgnore(WhenWritingDefault)] bypasses validation on inbound requests

Open glenndierckx opened this issue 3 weeks ago • 1 comments

Is there an existing issue for this?

  • [x] 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

glenndierckx avatar Dec 08 '25 09:12 glenndierckx

This happens because our current check for the JsonIgnore attribute is unconditional. We can resolve this by tightening up the check.

captainsafia avatar Dec 10 '25 20:12 captainsafia