Search code examples
c#asp.net-core-webapi.net-6.0imodelbinder

JSON binding in ASP.NET Core 6 Web API


The ASP.NET Core 6 Web API takes a view model that has a string property of Status. It turns out the Status internally is an enum called StatusEnum:

public enum StatusEnum
{
    Pending = 1,
    InProgress = 2,
    Completed = 3,
    Failed = 4,
    OnHold = 5
}

public class TaskViewModel
{
    public string Status { get; set; }
    public string TaskName { get; set; }
    public DateTime Deadline { get; set; }
}

All the C# code is expecting this Status to be the numeric value as a string ("1", "2", ...) but sometimes the client sends in the string name value ("Pending", "InProgress"), etc.

How would I go about creating a custom binding to convert the string name to the numeric value as a string?


Solution

  • Option 1) Add JsonStringEnumConverter in your application startup routine

    Option 2) Decorate the enum in question with [JsonConverter(typeof(JsonStringEnumConverter<MyEnum>))]

    https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/customize-properties?pivots=dotnet-8-0#enums-as-strings

    Edit: I'd missed that you said sometimes the client sends a string representation. With the behaviours provided in the framework it's one or the other, you'd have to customise to allow either - or just tell the clients not to do that. Requiring them to obey a reasonable API contract is perfectly acceptable.