Skip to content

Respect JsonSerializerOptions casing for property names in validation errors #62036

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 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
d3d01af
Initial plan for issue
Copilot May 20, 2025
03af06c
Add support for JsonSerializerOptions property naming policy in valid…
Copilot May 20, 2025
216406a
Make SerializerOptions property internal and retrieve options from DI
Copilot May 21, 2025
f92b43e
Refactor SerializerOptions property to dynamically access JsonOptions…
Copilot May 21, 2025
0900ced
Made SerializerOptions property public and added tests for formatting…
Copilot May 21, 2025
2694d90
Update ValidationEndpointFilterFactory to use type-safe DI for JsonOp…
Copilot May 21, 2025
193c6a7
Revert changes to package.json and package-lock.json files
Copilot May 21, 2025
c1cfc9e
Address review feedback: Add null check in FormatComplexKey and test …
Copilot May 21, 2025
28b6aa1
Format validation error messages to respect JSON naming policy
Copilot May 21, 2025
e94aff2
Update remaining tests to expect formatted error messages
Copilot May 21, 2025
9db960a
Fix member name formatting in validation errors
Copilot May 21, 2025
e9f9a2e
Fix validation error formatting
Copilot May 21, 2025
59069f7
Update tests and fix implementation for more cases
captainsafia May 28, 2025
10a3187
Merge branch 'main' into copilot/fix-61764-2
captainsafia May 28, 2025
2f5b553
Add PublicConstructors to DynamicallyAccessedMembers attribute in Val…
Copilot May 28, 2025
0ba6127
Merge branch 'main' into copilot/fix-61764-2
captainsafia May 29, 2025
f45c25a
Fix test after rebase
captainsafia May 29, 2025
d0e29c8
Merge branch 'main' into copilot/fix-61764-2
captainsafia May 29, 2025
409bb34
Cache HasDisplayAttribute and optimize FormatComplexKey performance
Copilot May 29, 2025
3cab762
Remove JSON naming policy formatting from ValidatableParameterInfo
Copilot May 29, 2025
f035b35
Move key formatting to ValidatableTypeInfo
captainsafia May 30, 2025
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
2 changes: 2 additions & 0 deletions src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidationContext.get -> Sy
Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidationContext.set -> void
Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidationErrors.get -> System.Collections.Generic.Dictionary<string!, string![]!>?
Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidationErrors.set -> void
Microsoft.AspNetCore.Http.Validation.ValidateContext.SerializerOptions.get -> System.Text.Json.JsonSerializerOptions?
Microsoft.AspNetCore.Http.Validation.ValidateContext.SerializerOptions.set -> void
Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidationOptions.get -> Microsoft.AspNetCore.Http.Validation.ValidationOptions!
Microsoft.AspNetCore.Http.Validation.ValidateContext.ValidationOptions.set -> void
Microsoft.AspNetCore.Http.Validation.ValidationOptions
Expand Down
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.AspNetCore.Http.Validation;

Expand All @@ -13,12 +16,13 @@ namespace Microsoft.AspNetCore.Http.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)]
Copy link
Member

Choose a reason for hiding this comment

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

Why is this necessary?

Type declaringType,
Type propertyType,
string name,
Expand All @@ -28,12 +32,16 @@ protected ValidatablePropertyInfo(
PropertyType = propertyType;
Name = name;
DisplayName = displayName;

// Cache the HasDisplayAttribute result to avoid repeated reflection calls
var property = DeclaringType.GetProperty(Name);
_hasDisplayAttribute = property is not null && HasDisplayAttribute(property);
Copy link
Member

Choose a reason for hiding this comment

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

Feels weird to grab the attribute, but then never actually use the value from the attribute. At that point, why not just use string.IsNullOrEmpty(DisplayName)?

Copy link
Member

Choose a reason for hiding this comment

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

Good catch. I find it sometimes helps to ask copilot not to add any fields if you don't think it should be necessary.

}

/// <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 +73,23 @@ public virtual async Task ValidateAsync(object? value, ValidateContext context,
var validationAttributes = GetValidationAttributes();

// Calculate and save the current path
var memberName = GetJsonPropertyName(Name, property, context.SerializerOptions?.PropertyNamingPolicy);
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, context.SerializerOptions?.PropertyNamingPolicy);
context.ValidationContext.MemberName = memberName;

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

/// <summary>
/// Gets the effective member name for JSON serialization, considering JsonPropertyName attribute 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 JsonPropertyName attribute 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 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 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
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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,17 @@ 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.
Copy link
Member

@halter73 halter73 Jun 5, 2025

Choose a reason for hiding this comment

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

Is this true? It's not like we're asking for the one and only [JsonPropertyName] used for the type represented by the ValidatableTypeInfo here. That would be impossible. Instead, we're asking for the [JsonPropertyName] for each of its member properties, right? If we didn't have any context of the property being validated here, how are we getting the name of the property at all let alone the proper casing?

I think we should probably respect all the same attributes we do in ValidatablePropertyInfo, namely [Display] (if we keep doing that) and [JsonPropertyName].

Copy link
Member

@halter73 halter73 Jun 5, 2025

Choose a reason for hiding this comment

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

Is this just redundant? Could it be that memberName already formatted here? I haven't run it, so it might not be the case, but we should definitely add some tests with a camel cased PropertyNamingPolicy and a capitalized first letter in the [JsonPropertyName] attribute.

var formattedMemberName = memberName;
if (context.SerializerOptions?.PropertyNamingPolicy != null)
{
formattedMemberName = context.SerializerOptions.PropertyNamingPolicy.ConvertName(memberName);
}

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

Expand Down
15 changes: 12 additions & 3 deletions src/Http/Http.Abstractions/src/Validation/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.Linq;
using System.Text.Json;

namespace Microsoft.AspNetCore.Http.Validation;

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

internal void AddValidationError(string key, string[] error)
/// <summary>
/// Gets or sets the JSON serializer options to use for property name formatting.
/// When available, property names in validation errors will be formatted according to the
/// PropertyNamingPolicy and JsonPropertyName attributes.
/// </summary>
public JsonSerializerOptions? SerializerOptions { get; set; }
Copy link
Member

Choose a reason for hiding this comment

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

Putting it on the record that I'm not a fan of adding this to the ValidateContext. Especially if we're wanting to eventually move this API into dotnet/runtime.

Copy link
Member

Choose a reason for hiding this comment

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

What do you think about moving it to ValidationOptions as I suggest here?


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

ValidationErrors[key] = error;
ValidationErrors[key] = errors;
}

internal void AddOrExtendValidationErrors(string key, string[] errors)
Expand All @@ -90,7 +99,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
Loading
Loading