Stop throwing when attempting to validate a JObject. (#71717)
authorArthur Vickers <ajcvickers@hotmail.com>
Mon, 11 Jul 2022 16:38:29 +0000 (17:38 +0100)
committerGitHub <noreply@github.com>
Mon, 11 Jul 2022 16:38:29 +0000 (17:38 +0100)
src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs
src/libraries/System.ComponentModel.Annotations/tests/System/ComponentModel/DataAnnotations/ValidatorTests.cs

index fd1af26..a145999 100644 (file)
@@ -518,7 +518,7 @@ namespace System.ComponentModel.DataAnnotations
         private static ICollection<KeyValuePair<ValidationContext, object?>> GetPropertyValues(object instance,
             ValidationContext validationContext)
         {
-            var properties = TypeDescriptor.GetProperties(instance);
+            var properties = TypeDescriptor.GetProperties(instance.GetType());
             var items = new List<KeyValuePair<ValidationContext, object?>>(properties.Count);
             foreach (PropertyDescriptor property in properties)
             {
index aef1542..b0985cd 100644 (file)
@@ -3,6 +3,7 @@
 
 using System.Collections.Generic;
 using System.Linq;
+using Newtonsoft.Json.Linq;
 using Xunit;
 
 namespace System.ComponentModel.DataAnnotations.Tests
@@ -333,6 +334,16 @@ namespace System.ComponentModel.DataAnnotations.Tests
             Assert.Contains(validationResults, x => x.ErrorMessage == "The SecondPropertyToBeTested field is not a valid phone number.");
         }
 
+        [Fact]
+        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework has always thrown for this case. See https://github.com/dotnet/runtime/issues/64207")]
+        public static void TryValidateObject_for_JObject_does_not_throw()
+        {
+            var objectToBeValidated = JObject.Parse("{\"Enabled\":true}");
+            var results = new List<ValidationResult>();
+            Assert.True(Validator.TryValidateObject(objectToBeValidated, new ValidationContext(objectToBeValidated), results, true));
+            Assert.Empty(results);
+        }
+
         public class RequiredFailure
         {
             [Required]