-
Notifications
You must be signed in to change notification settings - Fork 10.3k
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
Copilot
wants to merge
12
commits into
main
Choose a base branch
from
copilot/fix-61764-2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 9 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
d3d01af
Initial plan for issue
Copilot 03af06c
Add support for JsonSerializerOptions property naming policy in valid…
Copilot 216406a
Make SerializerOptions property internal and retrieve options from DI
Copilot f92b43e
Refactor SerializerOptions property to dynamically access JsonOptions…
Copilot 0900ced
Made SerializerOptions property public and added tests for formatting…
Copilot 2694d90
Update ValidationEndpointFilterFactory to use type-safe DI for JsonOp…
Copilot 193c6a7
Revert changes to package.json and package-lock.json files
Copilot c1cfc9e
Address review feedback: Add null check in FormatComplexKey and test …
Copilot 28b6aa1
Format validation error messages to respect JSON naming policy
Copilot e94aff2
Update remaining tests to expect formatted error messages
Copilot 9db960a
Fix member name formatting in validation errors
Copilot e9f9a2e
Fix validation error formatting
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,6 +3,8 @@ | |
|
||
using System.ComponentModel.DataAnnotations; | ||
using System.Diagnostics.CodeAnalysis; | ||
using System.Linq; | ||
using System.Text.Json; | ||
|
||
namespace Microsoft.AspNetCore.Http.Validation; | ||
|
||
|
@@ -59,42 +61,195 @@ 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> | ||
public JsonSerializerOptions? SerializerOptions { get; set; } | ||
|
||
internal void AddValidationError(string key, string[] error) | ||
internal void AddValidationError(string key, string[] errors) | ||
{ | ||
ValidationErrors ??= []; | ||
|
||
ValidationErrors[key] = error; | ||
var formattedKey = FormatKey(key); | ||
var formattedErrors = errors.Select(FormatErrorMessage).ToArray(); | ||
ValidationErrors[formattedKey] = formattedErrors; | ||
} | ||
|
||
internal void AddOrExtendValidationErrors(string key, string[] errors) | ||
{ | ||
ValidationErrors ??= []; | ||
|
||
if (ValidationErrors.TryGetValue(key, out var existingErrors)) | ||
var formattedKey = FormatKey(key); | ||
var formattedErrors = errors.Select(FormatErrorMessage).ToArray(); | ||
|
||
if (ValidationErrors.TryGetValue(formattedKey, out var existingErrors)) | ||
{ | ||
var newErrors = new string[existingErrors.Length + errors.Length]; | ||
var newErrors = new string[existingErrors.Length + formattedErrors.Length]; | ||
existingErrors.CopyTo(newErrors, 0); | ||
errors.CopyTo(newErrors, existingErrors.Length); | ||
ValidationErrors[key] = newErrors; | ||
formattedErrors.CopyTo(newErrors, existingErrors.Length); | ||
ValidationErrors[formattedKey] = newErrors; | ||
} | ||
else | ||
{ | ||
ValidationErrors[key] = errors; | ||
ValidationErrors[formattedKey] = formattedErrors; | ||
} | ||
} | ||
|
||
internal void AddOrExtendValidationError(string key, string error) | ||
{ | ||
ValidationErrors ??= []; | ||
|
||
if (ValidationErrors.TryGetValue(key, out var existingErrors) && !existingErrors.Contains(error)) | ||
var formattedKey = FormatKey(key); | ||
var formattedError = FormatErrorMessage(error); | ||
|
||
if (ValidationErrors.TryGetValue(formattedKey, out var existingErrors) && !existingErrors.Contains(formattedError)) | ||
{ | ||
ValidationErrors[key] = [.. existingErrors, error]; | ||
ValidationErrors[formattedKey] = [.. existingErrors, formattedError]; | ||
} | ||
else | ||
{ | ||
ValidationErrors[key] = [error]; | ||
ValidationErrors[formattedKey] = [formattedError]; | ||
} | ||
} | ||
|
||
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(); | ||
captainsafia marked this conversation as resolved.
Show resolved
Hide resolved
|
||
int lastIndex = 0; | ||
int i = 0; | ||
bool inBracket = false; | ||
var propertyNamingPolicy = SerializerOptions?.PropertyNamingPolicy; | ||
|
||
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 = propertyNamingPolicy is not null | ||
? propertyNamingPolicy.ConvertName(segment) | ||
: 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 = propertyNamingPolicy is not null | ||
? propertyNamingPolicy.ConvertName(segment) | ||
: 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 && propertyNamingPolicy is not null) | ||
{ | ||
segment = propertyNamingPolicy.ConvertName(segment); | ||
} | ||
result.Append(segment); | ||
} | ||
|
||
return result.ToString(); | ||
} | ||
|
||
// Format validation error messages to use the same property naming policy as the keys | ||
private string FormatErrorMessage(string errorMessage) | ||
captainsafia marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Delete this method and where it is invoked. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Deleted the FormatErrorMessage method and removed its invocations from the code in commit e9f9a2e. |
||
{ | ||
if (SerializerOptions?.PropertyNamingPolicy is null) | ||
{ | ||
return errorMessage; | ||
} | ||
|
||
// Common pattern: "The {PropertyName} field is required." | ||
const string pattern = "The "; | ||
const string fieldPattern = " field "; | ||
|
||
int startIndex = errorMessage.IndexOf(pattern, StringComparison.Ordinal); | ||
if (startIndex != 0) | ||
{ | ||
return errorMessage; // Does not start with "The " | ||
} | ||
|
||
int endIndex = errorMessage.IndexOf(fieldPattern, pattern.Length, StringComparison.Ordinal); | ||
if (endIndex <= pattern.Length) | ||
{ | ||
return errorMessage; // Does not contain " field " or it's too early | ||
} | ||
|
||
// Extract the property name between "The " and " field " | ||
// Use ReadOnlySpan<char> for better performance | ||
ReadOnlySpan<char> messageSpan = errorMessage.AsSpan(); | ||
ReadOnlySpan<char> propertyNameSpan = messageSpan.Slice(pattern.Length, endIndex - pattern.Length); | ||
string propertyName = propertyNameSpan.ToString(); | ||
|
||
if (string.IsNullOrWhiteSpace(propertyName)) | ||
{ | ||
return errorMessage; | ||
} | ||
|
||
// Format the property name with the naming policy | ||
string formattedPropertyName = SerializerOptions.PropertyNamingPolicy.ConvertName(propertyName); | ||
|
||
// Construct the new error message by combining parts | ||
return string.Concat( | ||
pattern, | ||
formattedPropertyName, | ||
messageSpan.Slice(endIndex).ToString() | ||
); | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.