Custom JsonConverter never gets called by the MVC model binder/controller

Viewed 342

I have a custom type that I want the MVC model binder serialize/deserialize using my custom JsonConverter for System.Text.Json. Here is my implementation:

public class Enumeration 
{
  private readonly string _value;

  public Enumeration(string value)
  {
    _value = value;
  }
  //utility methods
}

public class EmployeeTypeEnum : Enumeration
{
   EmployeeTypeEnum(string value) : base(value)
   {}

   public static implicit operator string(EmployeeTypeEnum employee)
   {
      return employee.Value
   }

   public static implicit operator EmployeeTypeEnum(string value)
   {
      return new EmployeeTypeEnum(value);
   }

   //Other util methods
}

Custom converter:

public class EmployeeTypeEnumJsonConvertor : System.Text.Json.Serialization.JsonConvertor<EmployeeTypeEnum>
{
     public override EmployeeTypeEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
     {
         //implementation
     }

     public override void Write(ref Utf8JsonWriter writer, EmployeeTypeEnum empEnum, JsonSerializerOptions options)
     {
         //implementation
     }
}

Type using the above:

public static class EmployeeType 
{
   public static readonly EmployeeTypeEnum Manager = "Manager";
}

Model using the employeeTypeEnum:

public class MyViewModel
{
   ...
   [JsonConverter(typeof(EmployeeTypeEnumJsonConvertor))]
   public EmployeTypeEnum EmployeeRank {get; set;}
   ...
}

Ajax call:

$.ajax({
   url: `https://localhost:8080/.../GetEmployeeRankInfo?Id=${id}&EmployeeRank=${rank}`,
   type: 'application/json',
   method: 'GET'
   ...
});

Controller:

public Task<IActionResult> GetEmployeeRankInfo(MyViewModel model)
{
   //Get employee Rank info
}

In the controller, the EmployeeRank is always null. I put a break point inside both Read and Write of the custom converter but none is hit. I also overrode the CanConvert method and not breaking in it there either. I went through a number of SO posts on this topic but most found a workaround. What could cause the custom serializer not to be called? Thanks

0 Answers
Related