Skip to content

Respect JsonSerializerOptions in validation errors #62341

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 79 additions & 6 deletions src/Validation/src/ValidatablePropertyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@

using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Microsoft.Extensions.Validation;

Expand All @@ -13,12 +16,13 @@ namespace Microsoft.Extensions.Validation;
public abstract class ValidatablePropertyInfo : IValidatableInfo
{
private RequiredAttribute? _requiredAttribute;
private readonly bool _hasDisplayAttribute;

/// <summary>
/// Creates a new instance of <see cref="ValidatablePropertyInfo"/>.
/// </summary>
protected ValidatablePropertyInfo(
[param: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)]
[param: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors)]
Type declaringType,
Type propertyType,
string name,
Expand All @@ -28,12 +32,18 @@ protected ValidatablePropertyInfo(
PropertyType = propertyType;
Name = name;
DisplayName = displayName;

// Cache the HasDisplayAttribute result to avoid repeated reflection calls
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Comment about why we don't use the name from the attribute

And maybe we should set DisplayName to the attributes value if the provided value happens to be null? (I know the API definition says non-null but...)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And maybe we should set DisplayName to the attributes value if the provided value happens to be null? (I know the API definition says non-null but...)

What would this help with?

// We only check for the existence of the DisplayAttribute here and not the
// Name value itself since we rely on the source generator populating it
var property = DeclaringType.GetProperty(Name);
Copy link
Preview

Copilot AI Jun 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Consider specifying explicit BindingFlags (e.g. BindingFlags.Public | BindingFlags.Instance) with GetProperty to ensure the lookup behavior is unambiguous.

Suggested change
var property = DeclaringType.GetProperty(Name);
var property = DeclaringType.GetProperty(Name, BindingFlags.Public | BindingFlags.Instance);

Copilot uses AI. Check for mistakes.

_hasDisplayAttribute = property is not null && HasDisplayAttribute(property);
}

/// <summary>
/// Gets the member type.
/// </summary>
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)]
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors)]
internal Type DeclaringType { get; }

/// <summary>
Expand Down Expand Up @@ -65,18 +75,24 @@ public virtual async Task ValidateAsync(object? value, ValidateContext context,
var validationAttributes = GetValidationAttributes();

// Calculate and save the current path
var namingPolicy = context.SerializerOptions?.PropertyNamingPolicy;
var memberName = GetJsonPropertyName(Name, property, namingPolicy);
var originalPrefix = context.CurrentValidationPath;
if (string.IsNullOrEmpty(originalPrefix))
{
context.CurrentValidationPath = Name;
context.CurrentValidationPath = memberName;
}
else
{
context.CurrentValidationPath = $"{originalPrefix}.{Name}";
context.CurrentValidationPath = $"{originalPrefix}.{memberName}";
}

context.ValidationContext.DisplayName = DisplayName;
context.ValidationContext.MemberName = Name;
// Format the display name and member name according to JsonPropertyName attribute first, then naming policy
// If the property has a [Display] attribute (either on property or record parameter), use DisplayName directly without formatting
context.ValidationContext.DisplayName = _hasDisplayAttribute
? DisplayName
: GetJsonPropertyName(DisplayName, property, namingPolicy);
context.ValidationContext.MemberName = memberName;

// Check required attribute first
if (_requiredAttribute is not null || validationAttributes.TryGetRequiredAttribute(out _requiredAttribute))
Expand Down Expand Up @@ -170,4 +186,61 @@ void ValidateValue(object? val, string errorPrefix, ValidationAttribute[] valida
}
}
}

/// <summary>
/// Gets the effective member name for JSON serialization, considering <see cref="JsonPropertyNameAttribute"/> and naming policy.
/// </summary>
/// <param name="targetValue">The target value to get the name for.</param>
/// <param name="property">The property info to get the name for.</param>
/// <param name="namingPolicy">The JSON naming policy to apply if no <see cref="JsonPropertyNameAttribute"/> is present.</param>
/// <returns>The effective property name for JSON serialization.</returns>
private static string GetJsonPropertyName(string targetValue, PropertyInfo property, JsonNamingPolicy? namingPolicy)
{
var jsonPropertyName = property.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name;

if (jsonPropertyName is not null)
{
return jsonPropertyName;
}

if (namingPolicy is not null)
{
return namingPolicy.ConvertName(targetValue);
}

return targetValue;
}

/// <summary>
/// Determines whether the property has a <see cref="DisplayAttribute"/>, either directly on the property
/// or on the corresponding constructor parameter if the declaring type is a record.
/// </summary>
/// <param name="property">The property to check.</param>
/// <returns>True if the property has a <see cref="DisplayAttribute"/> , false otherwise.</returns>
private bool HasDisplayAttribute(PropertyInfo property)
{
// Check if the property itself has the DisplayAttribute with a valid Name
if (property.GetCustomAttribute<DisplayAttribute>() is { Name: not null })
{
return true;
}

// Look for a constructor parameter matching the property name (case-insensitive)
// to account for the record scenario
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and primary ctors?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not quite since there isn't the same case-based 1:1 mapping between property names and parameter names when using primary constructors. It's a variation of #61526.

foreach (var constructor in DeclaringType.GetConstructors())
{
foreach (var parameter in constructor.GetParameters())
{
if (string.Equals(parameter.Name, property.Name, StringComparison.OrdinalIgnoreCase))
{
if (parameter.GetCustomAttribute<DisplayAttribute>() is { Name: not null })
{
return true;
}
}
}
}

return false;
}
}
8 changes: 6 additions & 2 deletions src/Validation/src/ValidatableTypeInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,13 @@ public virtual async Task ValidateAsync(object? value, ValidateContext context,
// Create a validation error for each member name that is provided
foreach (var memberName in validationResult.MemberNames)
{
// Format the member name using JsonSerializerOptions naming policy if available
// Note: we don't respect [JsonPropertyName] here because we have no context of the property being validated.
var formattedMemberName = context.SerializerOptions?.PropertyNamingPolicy?.ConvertName(memberName) ?? memberName;

var key = string.IsNullOrEmpty(originalPrefix) ?
memberName :
$"{originalPrefix}.{memberName}";
formattedMemberName :
$"{originalPrefix}.{formattedMemberName}";
context.AddOrExtendValidationError(key, validationResult.ErrorMessage);
}

Expand Down
51 changes: 49 additions & 2 deletions src/Validation/src/ValidateContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using Microsoft.Extensions.Options;

namespace Microsoft.Extensions.Validation;

Expand Down Expand Up @@ -60,10 +62,55 @@ public sealed class ValidateContext
/// </summary>
public int CurrentDepth { get; set; }

private JsonSerializerOptions? _cachedSerializerOptions;
private bool _serializerOptionsResolved;

internal JsonSerializerOptions? SerializerOptions
{
get
{
if (_serializerOptionsResolved)
{
return _cachedSerializerOptions;
}

_cachedSerializerOptions = ResolveSerializerOptions();
_serializerOptionsResolved = true;
return _cachedSerializerOptions;
}
}

/// <summary>
/// Attempts to resolve the <see cref="JsonSerializerOptions"/> used for serialization
/// using reflection to access JsonOptions from the ASP.NET Core shared framework.
/// </summary>
private JsonSerializerOptions? ResolveSerializerOptions()
{
var targetType = "Microsoft.AspNetCore.Http.Json.JsonOptions, Microsoft.AspNetCore.Http.Extensions";
var jsonOptionsType = Type.GetType(targetType, throwOnError: false);
if (jsonOptionsType is null)
{
return null;
}

var iOptionsType = typeof(IOptions<>).MakeGenericType(jsonOptionsType);

var optionsObj = ValidationContext.GetService(iOptionsType);
if (optionsObj is null)
{
return null;
}

var valueProp = iOptionsType.GetProperty("Value")!;
var jsonOptions = valueProp.GetValue(optionsObj);
var serializerProp = jsonOptionsType.GetProperty("SerializerOptions")!;

return serializerProp.GetValue(jsonOptions) as JsonSerializerOptions;
}

internal void AddValidationError(string key, string[] error)
{
ValidationErrors ??= [];

ValidationErrors[key] = error;
}

Expand All @@ -90,7 +137,7 @@ internal void AddOrExtendValidationError(string key, string error)

if (ValidationErrors.TryGetValue(key, out var existingErrors) && !existingErrors.Contains(error))
{
ValidationErrors[key] = [.. existingErrors, error];
ValidationErrors[key] = [..existingErrors, error];
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ async Task InvalidIntegerWithRangeProducesError(Endpoint endpoint)
var problemDetails = await AssertBadRequest(context);
Assert.Collection(problemDetails.Errors, kvp =>
{
Assert.Equal("IntegerWithRange", kvp.Key);
Assert.Equal("The field IntegerWithRange must be between 10 and 100.", kvp.Value.Single());
Assert.Equal("integerWithRange", kvp.Key);
Assert.Equal("The field integerWithRange must be between 10 and 100.", kvp.Value.Single());
});
}

Expand All @@ -145,7 +145,7 @@ async Task InvalidIntegerWithRangeAndDisplayNameProducesError(Endpoint endpoint)
var problemDetails = await AssertBadRequest(context);
Assert.Collection(problemDetails.Errors, kvp =>
{
Assert.Equal("IntegerWithRangeAndDisplayName", kvp.Key);
Assert.Equal("integerWithRangeAndDisplayName", kvp.Key);
Assert.Equal("The field Valid identifier must be between 10 and 100.", kvp.Value.Single());
});
}
Expand All @@ -164,8 +164,8 @@ async Task MissingRequiredSubtypePropertyProducesError(Endpoint endpoint)
var problemDetails = await AssertBadRequest(context);
Assert.Collection(problemDetails.Errors, kvp =>
{
Assert.Equal("PropertyWithMemberAttributes", kvp.Key);
Assert.Equal("The PropertyWithMemberAttributes field is required.", kvp.Value.Single());
Assert.Equal("propertyWithMemberAttributes", kvp.Key);
Assert.Equal("The propertyWithMemberAttributes field is required.", kvp.Value.Single());
});
}

Expand All @@ -187,13 +187,13 @@ async Task InvalidRequiredSubtypePropertyProducesError(Endpoint endpoint)
Assert.Collection(problemDetails.Errors,
kvp =>
{
Assert.Equal("PropertyWithMemberAttributes.RequiredProperty", kvp.Key);
Assert.Equal("The RequiredProperty field is required.", kvp.Value.Single());
Assert.Equal("propertyWithMemberAttributes.requiredProperty", kvp.Key);
Assert.Equal("The requiredProperty field is required.", kvp.Value.Single());
},
kvp =>
{
Assert.Equal("PropertyWithMemberAttributes.StringWithLength", kvp.Key);
Assert.Equal("The field StringWithLength must be a string with a maximum length of 10.", kvp.Value.Single());
Assert.Equal("propertyWithMemberAttributes.stringWithLength", kvp.Key);
Assert.Equal("The field stringWithLength must be a string with a maximum length of 10.", kvp.Value.Single());
});
}

Expand All @@ -216,18 +216,18 @@ async Task InvalidSubTypeWithInheritancePropertyProducesError(Endpoint endpoint)
Assert.Collection(problemDetails.Errors,
kvp =>
{
Assert.Equal("PropertyWithInheritance.EmailString", kvp.Key);
Assert.Equal("The EmailString field is not a valid e-mail address.", kvp.Value.Single());
Assert.Equal("propertyWithInheritance.emailString", kvp.Key);
Assert.Equal("The emailString field is not a valid e-mail address.", kvp.Value.Single());
},
kvp =>
{
Assert.Equal("PropertyWithInheritance.RequiredProperty", kvp.Key);
Assert.Equal("The RequiredProperty field is required.", kvp.Value.Single());
Assert.Equal("propertyWithInheritance.requiredProperty", kvp.Key);
Assert.Equal("The requiredProperty field is required.", kvp.Value.Single());
},
kvp =>
{
Assert.Equal("PropertyWithInheritance.StringWithLength", kvp.Key);
Assert.Equal("The field StringWithLength must be a string with a maximum length of 10.", kvp.Value.Single());
Assert.Equal("propertyWithInheritance.stringWithLength", kvp.Key);
Assert.Equal("The field stringWithLength must be a string with a maximum length of 10.", kvp.Value.Single());
});
}

Expand Down Expand Up @@ -259,18 +259,18 @@ async Task InvalidListOfSubTypesProducesError(Endpoint endpoint)
Assert.Collection(problemDetails.Errors,
kvp =>
{
Assert.Equal("ListOfSubTypes[0].RequiredProperty", kvp.Key);
Assert.Equal("The RequiredProperty field is required.", kvp.Value.Single());
Assert.Equal("listOfSubTypes[0].requiredProperty", kvp.Key);
Assert.Equal("The requiredProperty field is required.", kvp.Value.Single());
},
kvp =>
{
Assert.Equal("ListOfSubTypes[0].StringWithLength", kvp.Key);
Assert.Equal("The field StringWithLength must be a string with a maximum length of 10.", kvp.Value.Single());
Assert.Equal("listOfSubTypes[0].stringWithLength", kvp.Key);
Assert.Equal("The field stringWithLength must be a string with a maximum length of 10.", kvp.Value.Single());
},
kvp =>
{
Assert.Equal("ListOfSubTypes[1].StringWithLength", kvp.Key);
Assert.Equal("The field StringWithLength must be a string with a maximum length of 10.", kvp.Value.Single());
Assert.Equal("listOfSubTypes[1].stringWithLength", kvp.Key);
Assert.Equal("The field stringWithLength must be a string with a maximum length of 10.", kvp.Value.Single());
});
}

Expand All @@ -288,7 +288,7 @@ async Task InvalidPropertyWithDerivedValidationAttributeProducesError(Endpoint e
var problemDetails = await AssertBadRequest(context);
Assert.Collection(problemDetails.Errors, kvp =>
{
Assert.Equal("IntegerWithDerivedValidationAttribute", kvp.Key);
Assert.Equal("integerWithDerivedValidationAttribute", kvp.Key);
Assert.Equal("Value must be an even number", kvp.Value.Single());
});
}
Expand All @@ -297,7 +297,7 @@ async Task InvalidPropertyWithMultipleAttributesProducesError(Endpoint endpoint)
{
var payload = """
{
"PropertyWithMultipleAttributes": 5
"propertyWithMultipleAttributes": 5
}
""";
var context = CreateHttpContextWithPayload(payload, serviceProvider);
Expand All @@ -307,15 +307,15 @@ async Task InvalidPropertyWithMultipleAttributesProducesError(Endpoint endpoint)
var problemDetails = await AssertBadRequest(context);
Assert.Collection(problemDetails.Errors, kvp =>
{
Assert.Equal("PropertyWithMultipleAttributes", kvp.Key);
Assert.Equal("propertyWithMultipleAttributes", kvp.Key);
Assert.Collection(kvp.Value,
error =>
{
Assert.Equal("The field PropertyWithMultipleAttributes is invalid.", error);
Assert.Equal("The field propertyWithMultipleAttributes is invalid.", error);
},
error =>
{
Assert.Equal("The field PropertyWithMultipleAttributes must be between 10 and 100.", error);
Assert.Equal("The field propertyWithMultipleAttributes must be between 10 and 100.", error);
});
});
}
Expand All @@ -335,7 +335,7 @@ async Task InvalidPropertyWithCustomValidationProducesError(Endpoint endpoint)
var problemDetails = await AssertBadRequest(context);
Assert.Collection(problemDetails.Errors, kvp =>
{
Assert.Equal("IntegerWithCustomValidation", kvp.Key);
Assert.Equal("integerWithCustomValidation", kvp.Key);
var error = Assert.Single(kvp.Value);
Assert.Equal("Can't use the same number value in two properties on the same class.", error);
});
Expand Down
Loading
Loading