Skip to content

Add JsonIgnore attribute support to Minimal API validation generator #63075

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
merged 5 commits into from
Aug 4, 2025
Merged
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
2 changes: 2 additions & 0 deletions src/Shared/RoslynUtils/WellKnownTypeData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ public enum WellKnownType
Microsoft_AspNetCore_Authorization_IAuthorizeData,
System_AttributeUsageAttribute,
System_Text_Json_Serialization_JsonDerivedTypeAttribute,
System_Text_Json_Serialization_JsonIgnoreAttribute,
System_ComponentModel_DataAnnotations_DisplayAttribute,
System_ComponentModel_DataAnnotations_ValidationAttribute,
System_ComponentModel_DataAnnotations_RequiredAttribute,
Expand Down Expand Up @@ -240,6 +241,7 @@ public enum WellKnownType
"Microsoft.AspNetCore.Authorization.IAuthorizeData",
"System.AttributeUsageAttribute",
"System.Text.Json.Serialization.JsonDerivedTypeAttribute",
"System.Text.Json.Serialization.JsonIgnoreAttribute",
"System.ComponentModel.DataAnnotations.DisplayAttribute",
"System.ComponentModel.DataAnnotations.ValidationAttribute",
"System.ComponentModel.DataAnnotations.RequiredAttribute",
Expand Down
12 changes: 12 additions & 0 deletions src/Validation/gen/Extensions/ITypeSymbolExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,4 +152,16 @@ attr.AttributeClass is not null &&
(attr.AttributeClass.ImplementsInterface(fromServiceMetadataSymbol) ||
SymbolEqualityComparer.Default.Equals(attr.AttributeClass, fromKeyedServiceAttributeSymbol)));
}

/// <summary>
/// Checks if the property is marked with [JsonIgnore] attribute.
/// </summary>
/// <param name="property">The property to check.</param>
/// <param name="jsonIgnoreAttributeSymbol">The symbol representing the [JsonIgnore] attribute.</param>
internal static bool IsJsonIgnoredProperty(this IPropertySymbol property, INamedTypeSymbol jsonIgnoreAttributeSymbol)
{
return property.GetAttributes().Any(attr =>
attr.AttributeClass is not null &&
SymbolEqualityComparer.Default.Equals(attr.AttributeClass, jsonIgnoreAttributeSymbol));
Copy link
Member

@BrennanConroy BrennanConroy Aug 4, 2025

Choose a reason for hiding this comment

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

Not relevant for this change, but does this comparison work for derived types?
e.g. MyFromKeyedServicesAttribute : FromKeyedServicesAttribute

See code a few lines above

Copy link
Member

Choose a reason for hiding this comment

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

It won't, but JsonIgnoreAttribute is sealed so there's not likely to be derived types. FromKeyedServices is not.

Copy link
Member

Choose a reason for hiding this comment

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

So we should update the keyed service check in a separate PR

Copy link
Member

Choose a reason for hiding this comment

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

Yep -- we want to probably do an audit across the repo for anywhere we type check on FromKeyedServices and FromServices since both of those are unsealed.

}
}
1 change: 1 addition & 0 deletions src/Validation/gen/Models/RequiredSymbols.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ internal sealed record class RequiredSymbols(
INamedTypeSymbol IEnumerable,
INamedTypeSymbol IValidatableObject,
INamedTypeSymbol JsonDerivedTypeAttribute,
INamedTypeSymbol JsonIgnoreAttribute,
INamedTypeSymbol RequiredAttribute,
INamedTypeSymbol CustomValidationAttribute,
INamedTypeSymbol HttpContext,
Expand Down
14 changes: 14 additions & 0 deletions src/Validation/gen/Parsers/ValidationsGenerator.TypesParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ internal ImmutableArray<ValidatableProperty> ExtractValidatableMembers(ITypeSymb
WellKnownTypeData.WellKnownType.Microsoft_AspNetCore_Http_Metadata_IFromServiceMetadata);
var fromKeyedServiceAttributeSymbol = wellKnownTypes.Get(
WellKnownTypeData.WellKnownType.Microsoft_Extensions_DependencyInjection_FromKeyedServicesAttribute);
var jsonIgnoreAttributeSymbol = wellKnownTypes.Get(
WellKnownTypeData.WellKnownType.System_Text_Json_Serialization_JsonIgnoreAttribute);

// Special handling for record types to extract properties from
// the primary constructor.
Expand Down Expand Up @@ -148,6 +150,12 @@ internal ImmutableArray<ValidatableProperty> ExtractValidatableMembers(ITypeSymb
continue;
}

// Skip properties that have JsonIgnore attribute
if (correspondingProperty.IsJsonIgnoredProperty(jsonIgnoreAttributeSymbol))
Copy link
Preview

Copilot AI Aug 4, 2025

Choose a reason for hiding this comment

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

Consider adding a null check for jsonIgnoreAttributeSymbol before calling the extension method to handle cases where the symbol might not be available.

Copilot uses AI. Check for mistakes.

{
continue;
}

// Check if the property's type is validatable, this resolves
// validatable types in the inheritance hierarchy
var hasValidatableType = TryExtractValidatableType(
Expand Down Expand Up @@ -186,6 +194,12 @@ internal ImmutableArray<ValidatableProperty> ExtractValidatableMembers(ITypeSymb
continue;
}

// Skip properties that have JsonIgnore attribute
if (member.IsJsonIgnoredProperty(jsonIgnoreAttributeSymbol))
Copy link
Preview

Copilot AI Aug 4, 2025

Choose a reason for hiding this comment

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

Consider adding a null check for jsonIgnoreAttributeSymbol before calling the extension method to handle cases where the symbol might not be available.

Copilot uses AI. Check for mistakes.

{
continue;
}

var hasValidatableType = TryExtractValidatableType(member.Type, wellKnownTypes, ref validatableTypes, ref visitedTypes);
var attributes = ExtractValidationAttributes(member, wellKnownTypes, out var isRequired);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,153 @@ namespace Microsoft.Extensions.Validation.GeneratorTests;

public partial class ValidationsGeneratorTests : ValidationsGeneratorTestBase
{
[Fact]
public async Task CanValidateComplexTypesWithJsonIgnore()
{
// Arrange
var source = """
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Validation;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder();

builder.Services.AddValidation();

var app = builder.Build();

app.MapPost("/complex-type-with-json-ignore", (ComplexTypeWithJsonIgnore complexType) => Results.Ok("Passed"!));
app.MapPost("/record-type-with-json-ignore", (RecordTypeWithJsonIgnore recordType) => Results.Ok("Passed"!));

app.Run();

public class ComplexTypeWithJsonIgnore
{
[Range(10, 100)]
public int ValidatedProperty { get; set; } = 10;

[JsonIgnore]
[Required] // This should be ignored because of [JsonIgnore]
public string IgnoredProperty { get; set; } = null!;

[JsonIgnore]
public CircularReferenceType? CircularReference { get; set; }
}

public class CircularReferenceType
{
[JsonIgnore]
public ComplexTypeWithJsonIgnore? Parent { get; set; }

public string Name { get; set; } = "test";
}

public record RecordTypeWithJsonIgnore
{
[Range(10, 100)]
public int ValidatedProperty { get; set; } = 10;

[JsonIgnore]
[Required] // This should be ignored because of [JsonIgnore]
public string IgnoredProperty { get; set; } = null!;

[JsonIgnore]
public CircularReferenceRecord? CircularReference { get; set; }
}

public record CircularReferenceRecord
{
[JsonIgnore]
public RecordTypeWithJsonIgnore? Parent { get; set; }

public string Name { get; set; } = "test";
}
""";
await Verify(source, out var compilation);
await VerifyEndpoint(compilation, "/complex-type-with-json-ignore", async (endpoint, serviceProvider) =>
{
await ValidInputWithJsonIgnoreProducesNoWarnings(endpoint);
await InvalidValidatedPropertyProducesError(endpoint);

async Task ValidInputWithJsonIgnoreProducesNoWarnings(Endpoint endpoint)
{
var payload = """
{
"ValidatedProperty": 50
}
""";
var context = CreateHttpContextWithPayload(payload, serviceProvider);
await endpoint.RequestDelegate(context);

Assert.Equal(200, context.Response.StatusCode);
}

async Task InvalidValidatedPropertyProducesError(Endpoint endpoint)
{
var payload = """
{
"ValidatedProperty": 5
}
""";
var context = CreateHttpContextWithPayload(payload, serviceProvider);

await endpoint.RequestDelegate(context);

var problemDetails = await AssertBadRequest(context);
Assert.Collection(problemDetails.Errors, kvp =>
{
Assert.Equal("ValidatedProperty", kvp.Key);
Assert.Equal("The field ValidatedProperty must be between 10 and 100.", kvp.Value.Single());
});
}
});

await VerifyEndpoint(compilation, "/record-type-with-json-ignore", async (endpoint, serviceProvider) =>
{
await ValidInputWithJsonIgnoreProducesNoWarningsForRecord(endpoint);
await InvalidValidatedPropertyProducesErrorForRecord(endpoint);

async Task ValidInputWithJsonIgnoreProducesNoWarningsForRecord(Endpoint endpoint)
{
var payload = """
{
"ValidatedProperty": 50
}
""";
var context = CreateHttpContextWithPayload(payload, serviceProvider);
await endpoint.RequestDelegate(context);

Assert.Equal(200, context.Response.StatusCode);
}

async Task InvalidValidatedPropertyProducesErrorForRecord(Endpoint endpoint)
{
var payload = """
{
"ValidatedProperty": 5
}
""";
var context = CreateHttpContextWithPayload(payload, serviceProvider);

await endpoint.RequestDelegate(context);

var problemDetails = await AssertBadRequest(context);
Assert.Collection(problemDetails.Errors, kvp =>
{
Assert.Equal("ValidatedProperty", kvp.Key);
Assert.Equal("The field ValidatedProperty must be between 10 and 100.", kvp.Value.Single());
});
}
});
}
[Fact]
public async Task CanValidateComplexTypes()
{
Expand Down
Loading
Loading