-
Notifications
You must be signed in to change notification settings - Fork 10.7k
Use JSON Property Name attributes when creating ModelState Validation errors #39008
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
Merged
brunolins16
merged 17 commits into
dotnet:main
from
brunolins16:brunolins16/issues/17999-api-suggestions
Jan 7, 2022
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
c923ad2
Core functionality
brunolins16 bb9f808
Clean up
brunolins16 b1aea75
Moving to JsonOptions
brunolins16 03f2ea0
Moving from abstract to virtual
brunolins16 9ee5ee8
Removing from JSonOptions
brunolins16 f38f57c
Updating constructor
brunolins16 845a668
Removing from default
brunolins16 921a213
Renaming as suggested during API Review
brunolins16 cf15c79
Renaming as suggested during API Review
brunolins16 973fac1
Updating api
brunolins16 2aab9cd
Update src/Mvc/Mvc.Core/src/ModelBinding/Metadata/SystemTextJsonValid…
brunolins16 3e5dc81
Adding SystemTextJsonValidationMetadataProvider unit test
brunolins16 aba9851
Adding unittest
brunolins16 9777b52
Adding unit test
brunolins16 303ad78
Merge branch 'main' into brunolins16/issues/17999-api-suggestions
brunolins16 6536fe7
Fixing coding style
brunolins16 e0dcf08
Fix formatting
brunolins16 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
77 changes: 77 additions & 0 deletions
77
src/Mvc/Mvc.Core/src/ModelBinding/Metadata/SystemTextJsonValidationMetadataProvider.cs
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 |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| #nullable enable | ||
|
|
||
| using System.Linq; | ||
| using System.Text.Json; | ||
| using System.Text.Json.Serialization; | ||
|
|
||
| namespace Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; | ||
|
|
||
| /// <summary> | ||
| /// An implementation of <see cref="IDisplayMetadataProvider"/> and <see cref="IValidationMetadataProvider"/> for | ||
| /// the System.Text.Json.Serialization attribute classes. | ||
| /// </summary> | ||
| public sealed class SystemTextJsonValidationMetadataProvider : IDisplayMetadataProvider, IValidationMetadataProvider | ||
| { | ||
| private readonly JsonNamingPolicy _jsonNamingPolicy; | ||
|
|
||
| /// <summary> | ||
| /// Creates a new <see cref="SystemTextJsonValidationMetadataProvider"/> with the default <see cref="JsonNamingPolicy.CamelCase"/> | ||
| /// </summary> | ||
| public SystemTextJsonValidationMetadataProvider() | ||
| : this(JsonNamingPolicy.CamelCase) | ||
| { } | ||
|
|
||
| /// <summary> | ||
| /// Creates a new <see cref="SystemTextJsonValidationMetadataProvider"/> with an optional <see cref="JsonNamingPolicy"/> | ||
| /// </summary> | ||
| /// <param name="namingPolicy">The <see cref="JsonNamingPolicy"/> to be used to configure the metadata provider.</param> | ||
| public SystemTextJsonValidationMetadataProvider(JsonNamingPolicy namingPolicy) | ||
| { | ||
| if (namingPolicy == null) | ||
| { | ||
| throw new ArgumentNullException(nameof(namingPolicy)); | ||
| } | ||
|
|
||
| _jsonNamingPolicy = namingPolicy; | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public void CreateDisplayMetadata(DisplayMetadataProviderContext context) | ||
| { | ||
| if (context == null) | ||
| { | ||
| throw new ArgumentNullException(nameof(context)); | ||
| } | ||
|
|
||
| var propertyName = ReadPropertyNameFrom(context.Attributes); | ||
|
|
||
| if (!string.IsNullOrEmpty(propertyName)) | ||
| { | ||
| context.DisplayMetadata.DisplayName = () => propertyName; | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public void CreateValidationMetadata(ValidationMetadataProviderContext context) | ||
| { | ||
| if (context == null) | ||
| { | ||
| throw new ArgumentNullException(nameof(context)); | ||
| } | ||
|
|
||
| var propertyName = ReadPropertyNameFrom(context.Attributes); | ||
|
|
||
| if (string.IsNullOrEmpty(propertyName)) | ||
| { | ||
| propertyName = _jsonNamingPolicy.ConvertName(context.Key.Name!); | ||
| } | ||
|
|
||
| context.ValidationMetadata.ValidationModelName = propertyName; | ||
| } | ||
|
|
||
| private static string? ReadPropertyNameFrom(IReadOnlyList<object> attributes) | ||
| => attributes?.OfType<JsonPropertyNameAttribute>().FirstOrDefault()?.Name; | ||
| } |
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
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 |
|---|---|---|
| @@ -1 +1,8 @@ | ||
| #nullable enable | ||
| Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.SystemTextJsonValidationMetadataProvider | ||
| Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.SystemTextJsonValidationMetadataProvider.CreateDisplayMetadata(Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DisplayMetadataProviderContext! context) -> void | ||
| Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.SystemTextJsonValidationMetadataProvider.CreateValidationMetadata(Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.ValidationMetadataProviderContext! context) -> void | ||
| Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.SystemTextJsonValidationMetadataProvider.SystemTextJsonValidationMetadataProvider() -> void | ||
| Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.SystemTextJsonValidationMetadataProvider.SystemTextJsonValidationMetadataProvider(System.Text.Json.JsonNamingPolicy! namingPolicy) -> void | ||
| Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.ValidationMetadata.ValidationModelName.get -> string? | ||
| Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.ValidationMetadata.ValidationModelName.set -> void |
92 changes: 92 additions & 0 deletions
92
src/Mvc/Mvc.Core/test/ModelBinding/Metadata/SystemTextJsonValidationMetadataProviderTest.cs
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 |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Text.Json; | ||
| using System.Text.Json.Serialization; | ||
|
|
||
| namespace Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; | ||
|
|
||
| public class SystemTextJsonValidationMetadataProviderTest | ||
| { | ||
| [Fact] | ||
| public void CreateValidationMetadata_SetValidationPropertyName_WithJsonPropertyNameAttribute() | ||
| { | ||
| var metadataProvider = new SystemTextJsonValidationMetadataProvider(); | ||
| var propertyName = "sample-data"; | ||
|
|
||
| var key = ModelMetadataIdentity.ForProperty(typeof(SampleTestClass).GetProperty(nameof(SampleTestClass.NoAttributesProperty)), typeof(int), typeof(SampleTestClass)); | ||
| var modelAttributes = new ModelAttributes(Array.Empty<object>(), new[] { new JsonPropertyNameAttribute(propertyName) }, Array.Empty<object>()); | ||
| var context = new ValidationMetadataProviderContext(key, modelAttributes); | ||
|
|
||
| // Act | ||
| metadataProvider.CreateValidationMetadata(context); | ||
|
|
||
| // Assert | ||
| Assert.NotNull(context.ValidationMetadata.ValidationModelName); | ||
| Assert.Equal(propertyName, context.ValidationMetadata.ValidationModelName); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void CreateValidationMetadata_SetValidationPropertyName_CamelCaseWithDefaultNamingPolicy() | ||
| { | ||
| var metadataProvider = new SystemTextJsonValidationMetadataProvider(); | ||
| var propertyName = nameof(SampleTestClass.NoAttributesProperty); | ||
|
|
||
| var key = ModelMetadataIdentity.ForProperty(typeof(SampleTestClass).GetProperty(propertyName), typeof(int), typeof(SampleTestClass)); | ||
| var modelAttributes = new ModelAttributes(Array.Empty<object>(), Array.Empty<object>(), Array.Empty<object>()); | ||
| var context = new ValidationMetadataProviderContext(key, modelAttributes); | ||
|
|
||
| // Act | ||
| metadataProvider.CreateValidationMetadata(context); | ||
|
|
||
| // Assert | ||
| Assert.NotNull(context.ValidationMetadata.ValidationModelName); | ||
| Assert.Equal(JsonNamingPolicy.CamelCase.ConvertName(propertyName), context.ValidationMetadata.ValidationModelName); | ||
| } | ||
|
|
||
| [Theory] | ||
| [MemberData(nameof(NamingPolicies))] | ||
| public void CreateValidationMetadata_SetValidationPropertyName_WithJsonNamingPolicy(JsonNamingPolicy namingPolicy) | ||
| { | ||
| var metadataProvider = new SystemTextJsonValidationMetadataProvider(namingPolicy); | ||
| var propertyName = nameof(SampleTestClass.NoAttributesProperty); | ||
|
|
||
| var key = ModelMetadataIdentity.ForProperty(typeof(SampleTestClass).GetProperty(propertyName), typeof(int), typeof(SampleTestClass)); | ||
| var modelAttributes = new ModelAttributes(Array.Empty<object>(), Array.Empty<object>(), Array.Empty<object>()); | ||
| var context = new ValidationMetadataProviderContext(key, modelAttributes); | ||
|
|
||
| // Act | ||
| metadataProvider.CreateValidationMetadata(context); | ||
|
|
||
| // Assert | ||
| Assert.NotNull(context.ValidationMetadata.ValidationModelName); | ||
| Assert.Equal(namingPolicy.ConvertName(propertyName), context.ValidationMetadata.ValidationModelName); | ||
| } | ||
|
|
||
| public static TheoryData<JsonNamingPolicy> NamingPolicies | ||
| { | ||
| get | ||
| { | ||
| return new TheoryData<JsonNamingPolicy> | ||
| { | ||
| UpperCaseJsonNamingPolicy.Instance, | ||
| JsonNamingPolicy.CamelCase | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| public class UpperCaseJsonNamingPolicy : System.Text.Json.JsonNamingPolicy | ||
| { | ||
| public static JsonNamingPolicy Instance = new UpperCaseJsonNamingPolicy(); | ||
|
|
||
| public override string ConvertName(string name) | ||
| { | ||
| return name?.ToUpperInvariant(); | ||
| } | ||
| } | ||
|
|
||
| public class SampleTestClass | ||
| { | ||
| public int NoAttributesProperty { get; set; } | ||
| } | ||
| } |
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
76 changes: 76 additions & 0 deletions
76
src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonValidationMetadataProvider.cs
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 |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Linq; | ||
| using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; | ||
| using Newtonsoft.Json; | ||
| using Newtonsoft.Json.Serialization; | ||
|
|
||
| namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson; | ||
|
|
||
| /// <summary> | ||
| /// An implementation of <see cref="IDisplayMetadataProvider"/> and <see cref="IValidationMetadataProvider"/> for | ||
| /// the Newtonsoft.Json attribute classes. | ||
| /// </summary> | ||
| public sealed class NewtonsoftJsonValidationMetadataProvider : IDisplayMetadataProvider, IValidationMetadataProvider | ||
| { | ||
| private readonly NamingStrategy _jsonNamingPolicy; | ||
|
|
||
| /// <summary> | ||
| /// Creates a new <see cref="NewtonsoftJsonValidationMetadataProvider"/> with the default <see cref="CamelCaseNamingStrategy"/> | ||
| /// </summary> | ||
| public NewtonsoftJsonValidationMetadataProvider() | ||
| : this(new CamelCaseNamingStrategy()) | ||
| { } | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of <see cref="NewtonsoftJsonValidationMetadataProvider"/> with an optional <see cref="NamingStrategy"/> | ||
| /// </summary> | ||
| /// <param name="namingStrategy">The <see cref="NamingStrategy"/> to be used to configure the metadata provider.</param> | ||
| public NewtonsoftJsonValidationMetadataProvider(NamingStrategy namingStrategy) | ||
| { | ||
| if (namingStrategy == null) | ||
| { | ||
| throw new ArgumentNullException(nameof(namingStrategy)); | ||
| } | ||
|
|
||
| _jsonNamingPolicy = namingStrategy; | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public void CreateDisplayMetadata(DisplayMetadataProviderContext context) | ||
| { | ||
| if (context == null) | ||
| { | ||
| throw new ArgumentNullException(nameof(context)); | ||
| } | ||
|
|
||
| var propertyName = ReadPropertyNameFrom(context.Attributes); | ||
|
|
||
| if (!string.IsNullOrEmpty(propertyName)) | ||
| { | ||
| context.DisplayMetadata.DisplayName = () => propertyName; | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public void CreateValidationMetadata(ValidationMetadataProviderContext context) | ||
| { | ||
| if (context == null) | ||
| { | ||
| throw new ArgumentNullException(nameof(context)); | ||
| } | ||
|
|
||
| var propertyName = ReadPropertyNameFrom(context.Attributes); | ||
|
|
||
| if (string.IsNullOrEmpty(propertyName)) | ||
| { | ||
| propertyName = _jsonNamingPolicy.GetPropertyName(context.Key.Name!, false); | ||
| } | ||
|
|
||
| context.ValidationMetadata.ValidationModelName = propertyName!; | ||
| } | ||
|
|
||
| private static string? ReadPropertyNameFrom(IReadOnlyList<object> attributes) | ||
| => attributes?.OfType<JsonPropertyAttribute>().FirstOrDefault()?.PropertyName; | ||
| } |
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 |
|---|---|---|
| @@ -1 +1,6 @@ | ||
| #nullable enable | ||
| Microsoft.AspNetCore.Mvc.NewtonsoftJson.NewtonsoftJsonValidationMetadataProvider | ||
| Microsoft.AspNetCore.Mvc.NewtonsoftJson.NewtonsoftJsonValidationMetadataProvider.CreateDisplayMetadata(Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DisplayMetadataProviderContext! context) -> void | ||
| Microsoft.AspNetCore.Mvc.NewtonsoftJson.NewtonsoftJsonValidationMetadataProvider.CreateValidationMetadata(Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.ValidationMetadataProviderContext! context) -> void | ||
| Microsoft.AspNetCore.Mvc.NewtonsoftJson.NewtonsoftJsonValidationMetadataProvider.NewtonsoftJsonValidationMetadataProvider() -> void | ||
| Microsoft.AspNetCore.Mvc.NewtonsoftJson.NewtonsoftJsonValidationMetadataProvider.NewtonsoftJsonValidationMetadataProvider(Newtonsoft.Json.Serialization.NamingStrategy! namingStrategy) -> void |
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.