I want to get an array of polymorphic classes in a request:

{
    "notifications": [{"type":"Sms", ...}, {"type":"Email", ...}  ]
}

For that I have this code:

[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(EmailNotificationWeb), "Email")]
[JsonDerivedType(typeof(SmsNotificationWeb), "Sms")]
public abstract record NotificationWeb;

public record EmailNotificationWeb : NotificationWeb
{
    public required string Subject { get; init; }
    public required string Body { get; init; }
}

public record SmsNotificationWeb : NotificationWeb
{
    public required string Message { get; init; }
}

This works when I send elements of the array that contain "type", and even if "type" is wrong, then I get an error that the type is unknown.

But if I do not send the type discriminator at all, the request would just fail badly as it tries to create an abstract class. Is there any way to have a good message, like that the discriminator is not valid (same for say "type": "unknown", and absence of type).

1

There are 1 best solutions below

0
On

I have found that this little workaround works, but I would rather have something out of the box in Asp.Net Core ideally, as this would really mean I have to write it for every base class.

public record NotificationWeb : IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (GetType() == typeof(NotificationWeb))
        {
            yield return new ValidationResult("Type should be specified");   
        }
    }
}