[release/9.0] Ensure required properties are validated before invoking the deserialization constructor. #107126
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Backport of #107083 to release/9.0
/cc @eiriktsarpalis
Customer Impact
.NET 9 introduces the
JsonSerializerOptions.RespectRequiredConstructorParameters
property that enables treating non-optional constructor parameters as required in the JSON payload when deserializing an object. This builds upon existing infrastructure for properties markedrequired
. It has been reported by a customer that this validation is being run after the deserialization constructor has been invoked, meaning that uninitialized parameters could be passed to the constructor even with validation turned on. The issue typically manifests as exceptions being surfaced from the constructor itself (NRE or ArgumentException usually) as opposed to the expectedJsonException
detailing which required parameter is missing from the payload.Regression
Testing
Added unit testing validating the impacted use case.
Risk
Low. The change is a straightforward moving of required parameter validation to the top of the deserialization methods. Pedantically speaking this could be seen as a behavior change in cases where deserialization constructors perform side-effects, however that's an unlikely scenario we don't want to condone or support.