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

Draft
wants to merge 21 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 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
142 changes: 135 additions & 7 deletions src/Http/Http.Abstractions/src/Validation/ValidateContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

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

namespace Microsoft.AspNetCore.Http.Validation;

Expand Down Expand Up @@ -59,42 +60,169 @@ public sealed class ValidateContext
/// This is used to prevent stack overflows from circular references.
/// </summary>
public int CurrentDepth { get; set; }

/// <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>
internal JsonSerializerOptions? SerializerOptions
{
get
{
// If explicit options have been set, use those (primarily for testing)
if (_serializerOptions is not null)
{
return _serializerOptions;
}

// Otherwise try to get them from DI
var jsonOptionsType = Type.GetType("Microsoft.AspNetCore.Http.Json.JsonOptions, Microsoft.AspNetCore.Http.Extensions");
if (jsonOptionsType is null)
{
return null;
}

var jsonOptionsService = ValidationContext.GetService(jsonOptionsType);
if (jsonOptionsService is null)
{
return null;
}

// Get the SerializerOptions property via reflection
var serializerOptionsProperty = jsonOptionsType.GetProperty("SerializerOptions");
return serializerOptionsProperty?.GetValue(jsonOptionsService) as JsonSerializerOptions;
}
set => _serializerOptions = value;
}

private JsonSerializerOptions? _serializerOptions;

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

ValidationErrors[key] = error;
var formattedKey = FormatKey(key);
ValidationErrors[formattedKey] = error;
}

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

if (ValidationErrors.TryGetValue(key, out var existingErrors))
var formattedKey = FormatKey(key);
if (ValidationErrors.TryGetValue(formattedKey, out var existingErrors))
{
var newErrors = new string[existingErrors.Length + errors.Length];
existingErrors.CopyTo(newErrors, 0);
errors.CopyTo(newErrors, existingErrors.Length);
ValidationErrors[key] = newErrors;
ValidationErrors[formattedKey] = newErrors;
}
else
{
ValidationErrors[key] = errors;
ValidationErrors[formattedKey] = errors;
}
}

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

if (ValidationErrors.TryGetValue(key, out var existingErrors) && !existingErrors.Contains(error))
var formattedKey = FormatKey(key);
if (ValidationErrors.TryGetValue(formattedKey, out var existingErrors) && !existingErrors.Contains(error))
{
ValidationErrors[key] = [.. existingErrors, error];
ValidationErrors[formattedKey] = [.. existingErrors, error];
}
else
{
ValidationErrors[key] = [error];
ValidationErrors[formattedKey] = [error];
}
}

private string FormatKey(string key)
{
if (string.IsNullOrEmpty(key) || SerializerOptions?.PropertyNamingPolicy is null)
{
return key;
}

// If the key contains a path (e.g., "Address.Street" or "Items[0].Name"),
// apply the naming policy to each part of the path
if (key.Contains('.') || key.Contains('['))
{
return FormatComplexKey(key);
}

// Apply the naming policy directly
return SerializerOptions.PropertyNamingPolicy.ConvertName(key);
}

private string FormatComplexKey(string key)
{
// Use a more direct approach for complex keys with dots and array indices
var result = new System.Text.StringBuilder();
int lastIndex = 0;
int i = 0;
bool inBracket = false;

while (i < key.Length)
{
char c = key[i];

if (c == '[')
{
// Format the segment before the bracket
if (i > lastIndex)
{
string segment = key.Substring(lastIndex, i - lastIndex);
string formattedSegment = SerializerOptions!.PropertyNamingPolicy!.ConvertName(segment);
result.Append(formattedSegment);
}

// Start collecting the bracket part
inBracket = true;
result.Append(c);
lastIndex = i + 1;
}
else if (c == ']')
{
// Add the content inside the bracket as-is
if (i > lastIndex)
{
string segment = key.Substring(lastIndex, i - lastIndex);
result.Append(segment);
}
result.Append(c);
inBracket = false;
lastIndex = i + 1;
}
else if (c == '.' && !inBracket)
{
// Format the segment before the dot
if (i > lastIndex)
{
string segment = key.Substring(lastIndex, i - lastIndex);
string formattedSegment = SerializerOptions!.PropertyNamingPolicy!.ConvertName(segment);
result.Append(formattedSegment);
}
result.Append(c);
lastIndex = i + 1;
}

i++;
}

// Format the last segment if there is one
if (lastIndex < key.Length)
{
string segment = key.Substring(lastIndex);
if (!inBracket)
{
segment = SerializerOptions!.PropertyNamingPolicy!.ConvertName(segment);
}
result.Append(segment);
}

return result.ToString();
}
}
Loading
Loading