Skip to content

[JsonIgnore(WhenWritingDefault)] bypasses validation on inbound requests #64692

@glenndierckx

Description

@glenndierckx

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

Metadata

Metadata

Assignees

Labels

area-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcfeature-validationIssues related to model validation in minimal and controller-based APIs

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions