How to bind array of string to List of Enum in DTO class - C# WebApi

Viewed 189

I have a DTO record like so:

public record MessageDto {
    [Required] 
    public string Content { get; init; }

    public List<MessageType> Types { get; init;}
}

where MessageType looks like this:

public enum MessageType {
    Sms,
    Email
}

Now, when I'm sending this json message via API it all works (in this case, sms shows as binded element in Types:

{
  "content": "test",
  "types": [
    0
  ]
}

but when I'm sending json like this:

{
  "content": "test",
  "types": [
    "Sms"
  ]
}

I'm getting 400 Error: Bad Request.

Controller is very basic:

[HttpPost]
public async Task<ActionResult> PostAsync([FromBody] MessageDto messageDto) {
    // Body...
}

This string "Sms" doesn't bind to Types list. How can I force this kind of binding from array of string to list of enums?

0 Answers
Related