1

System.Text.Json のカスタム JsonConverter を使用して、MVC モデル バインダーをシリアル化/逆シリアル化するカスタム タイプがあります。これが私の実装です:

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
}

カスタム コンバーター:

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
     }
}

上記を使用して入力します。

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

employeeTypeEnum を使用したモデル:

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

Ajax 呼び出し:

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

コントローラ:

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

コントローラーでは、EmployeeRank は常に null です。カスタム コンバーターの Read と Write の両方にブレーク ポイントを設定しましたが、ヒットしません。また、CanConvert メソッドをオーバーライドし、そこでも中断しませんでした。このトピックに関する多くの SO 投稿を調べましたが、ほとんどが回避策を見つけました。カスタムシリアライザーが呼び出されない原因は何ですか? ありがとう

4

0 に答える 0