From 01eb3cc1638416f752e690064967ce7d4c173f03 Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Mon, 14 Sep 2020 17:38:25 +0200 Subject: [PATCH] Fixed: crash when building ModelState error response It may happen that `propertyName` contains something like 'Parent.Child.Some', so `property` becomes `null` and we crash on the next line with a `NullReferenceException`. This fix returns the original value if we are unable to translate between private/public names. --- .../Errors/InvalidModelStateException.cs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/JsonApiDotNetCore/Errors/InvalidModelStateException.cs b/src/JsonApiDotNetCore/Errors/InvalidModelStateException.cs index 038dee1166..d663a9bad8 100644 --- a/src/JsonApiDotNetCore/Errors/InvalidModelStateException.cs +++ b/src/JsonApiDotNetCore/Errors/InvalidModelStateException.cs @@ -34,10 +34,7 @@ private static IReadOnlyCollection FromModelState(ModelStateDictionary mo foreach (var (propertyName, entry) in modelState.Where(x => x.Value.Errors.Any())) { - PropertyInfo property = resourceType.GetProperty(propertyName); - - string attributeName = - property.GetCustomAttribute().PublicName ?? namingStrategy.GetPropertyName(property.Name, false); + string attributeName = GetDisplayNameForProperty(propertyName, resourceType, namingStrategy); foreach (var modelError in entry.Errors) { @@ -55,6 +52,19 @@ private static IReadOnlyCollection FromModelState(ModelStateDictionary mo return errors; } + private static string GetDisplayNameForProperty(string propertyName, Type resourceType, + NamingStrategy namingStrategy) + { + PropertyInfo property = resourceType.GetProperty(propertyName); + if (property != null) + { + var attrAttribute = property.GetCustomAttribute(); + return attrAttribute?.PublicName ?? namingStrategy.GetPropertyName(property.Name, false); + } + + return propertyName; + } + private static Error FromModelError(ModelError modelError, string attributeName, bool includeExceptionStackTraceInErrors) {