Custom EnumConverter being ignored by WebAPI databinding

Viewed 50

I have the following enum and EnumConverter:

[TypeConverter(typeof(MyEnumConverter))]
public enum MyEventType {
  Unknown,
  URLEvent
}

public class MyEnumConverter : EnumConverter
{
    public MyEnumConverter(Type type) : base(type)
    {
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        if (value is string)
        {
            var enumString = (string)value;
            return EnumExtensions.GetValueFromDescription(enumString, EnumType);
        }
        return base.ConvertFrom(context, culture, value);
    }
}

I also have a WebAPI controller that accepts an object that contains a property of the above enum type:

[Route("api/v1/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
   [Route("events")]
   [HttpPost]
   public IActionResult HandlePost([FromBody] MyEvent myEvent)
   {
       // Do whatever here
   }
}

public class MyEvent 
{
   public MyEventType eventType {get; set;}
}

However, if I POST {"eventType" : "URLEvent"} to the controller, I get an error: "The JSON value could not be converted ..." Placing a break-point in ConvertFrom() I can see that the it is never being called.

What do I need to do to get the Web API databinding to use my EnumConverter?

1 Answers

Here are two alternatives to solve your current problem:

First:System.Text.Json serialization:

services
    .AddMvc()
    // Or .AddControllers(...)
    .AddJsonOptions(opts =>
    {
        var enumConverter = new JsonStringEnumConverter();
        opts.JsonSerializerOptions.Converters.Add(enumConverter);
    })

The documentation can be found here.

Second:Newtonsoft.Json

Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson

And then:

services.AddControllers().AddNewtonsoftJson();

Test Result:

enter image description here

enter image description here

Related