Skip to content

DataAnnotations validation not supported for properties of nested values. #98430

Open
@ilya-scale

Description

@ilya-scale

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions