Fix issue with server validation from dictionary configuration where floating point values can be be accessed as doubles or ints (#18508)

* Fix issue with server validation from dictionary configuration where floating point values can be be accessed as doubles or ints.

* Fixed typo in comment.

---------

Co-authored-by: Mole <nikolajlauridsen@protonmail.ch>
This commit is contained in:
Andy Butland
2025-03-04 14:46:54 +01:00
parent d164892619
commit 51223f44ff
2 changed files with 73 additions and 8 deletions

View File

@@ -21,7 +21,7 @@ public abstract class DictionaryConfigurationValidatorBase
return false;
}
if (configuration.TryGetValue(key, out object? obj) && obj is TValue castValue)
if (configuration.TryGetValue(key, out object? obj) && TryCastValue(obj, out TValue? castValue))
{
value = castValue;
return true;
@@ -30,4 +30,24 @@ public abstract class DictionaryConfigurationValidatorBase
value = default;
return false;
}
private static bool TryCastValue<TValue>(object? value, [NotNullWhen(true)] out TValue? castValue)
{
if (value is TValue valueAsType)
{
castValue = valueAsType;
return true;
}
// Special case for floating point numbers - when deserialized these will be integers if whole numbers rather
// than double.
if (typeof(TValue) == typeof(double) && value is int valueAsInt)
{
castValue = (TValue)(object)Convert.ToDouble(valueAsInt);
return true;
}
castValue = default;
return false;
}
}