runtime: DataAnnotations validation not supported for properties of nested values.

Description

I have a polymorphic class like:

public record Request
{
    public required Base Prop { get; init; } 
}

[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(Derived), "derived")]
public abstract record Base
{
}

public record Derived : Base
{
    
    [Required, StringLength(1)]
    public string? Field { get; init; }
}

and 2 methods

[HttpPost("test-property")]
public void Test(Request request)
{
    
}

[HttpPost("test-request")]
public void Test(Base request)
{
    
}

This request to “test-property” results in 200 (which is incorrect since the field “field” is not specified):

{
	"prop": {
		"type": "derived"
	}
}

while a request to “test-request” results in 400 (“The Field field is required.” which is correct):

{
	"type": "derived"
}

Reproduction Steps

  1. Use the action methods described in the description
  2. Run the described payloads on both methods

Expected behavior

Both tests should result in a 400 since field “field” is not provided.

Actual behavior

Only one of them results in 400. If the property is polymorphic, then the validation does not work (it is not only the Required attribute that is affected)

Regression?

No response

Known Workarounds

No response

Configuration

.Net 8 Mac OS ARM

Other information

No response

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 3
  • Comments: 22 (14 by maintainers)

Most upvoted comments

It got routed to System.Text.Json ironically enough since I wrote explicitly it should not be 😃 (I guess the bot just found out that substring and did it)

It’s because dotnet/runtime doesn’t contain aspnet components. That’s fine, I transferred it to the relevant repo.

@danroth27 How does this work with AOT?

We don’t currently support Native AOT with our web UI frameworks like MVC, Razor Pages, and Blazor. Blazor does support AOT for WebAssembly, but we haven’t yet shipped support for full object validation for Blazor: https://github.com/dotnet/aspnetcore/issues/28640

This suggests to me that aspnetcore is using a separate validation engine, can anybody from @dotnet/aspnet-team confirm this?

Correct, ASP.NET Core does its own object traversal for validation.

If I understood correctly, then ValidateObjectMembersAttribute is what has solved the issue in the 1.

No, ValidateObjectMembersAttribute is part of a separate component, the options validator, that uses the same validation attributes.