【问题标题】:.NET Core/5 Deserialize with custom NewtonSoft converter but model still binds as null.NET Core/5 使用自定义 NewtonSoft 转换器反序列化,但模型仍绑定为 null
【发布时间】:2021-08-07 19:15:13
【问题描述】:

我正在尝试反序列化 .NET 5 api 项目中的子类。即使正在调用我的自定义 JSON 转换器并返回正确的对象,模型绑定器也会返回 null。

为了实现多态反序列化,我使用 NewtonSoft 序列化程序,添加如下:

services
 .AddControllers()
 .AddNewtonsoftJson(opts =>
 {
  opts.SerializerSettings.Converters.Insert(0, new RecordJsonConverter());
 });

我已将 Microsoft.AspNetCore.Mvc.NewtonsoftJson 添加到项目中。

类是这样的:

public class RecordDTO
{
 [...]
}

public class ARecordDTO : RecordDTO
{
 [...]
}

控制器接受基类:

public async override Task<IActionResult> Post([FromBody] RecordDTO dto)

还有 JSON 转换器:

 public class RecordJsonConverter : JsonConverter
    {
        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }

        public override bool CanRead
        {
            get
            {
                return true;
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override bool CanConvert(Type objectType)
        {
            // Only objects of the base type RecordDTO need to be converted by this custom converter.
            // If it is already knows which derived class it is, then we
            // can just let it use the standard converter.

            var recordType = typeof(RecordDTO);
            return recordType.IsAssignableFrom(objectType) && !objectType.IsSubclassOf(recordType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            [...]

            return target;
        }
    }

当我发布 ARecordDTO 对象时,我看到自定义 RecordJsonConverter 上的 ReadJson 被调用并填写了 ARecord 对象并正确返回。

然后我们回到控制器动作内部,dto 参数现在为空,而不是刚刚为绑定创建的 ARecordDTO。

有没有其他人遇到过这种情况?什么会导致 JSON 转换器返回的对象在绑定过程中被丢弃?

【问题讨论】:

    标签: c# asp.net-core model-binding .net-5


    【解决方案1】:

    好吧,以防其他人出现在这里并且同样不知情:

    如果 ModelState 中存在任何错误,则 action 参数将绑定为 null(而不是跳过有问题的单个字段并返回对象的其余部分,这是我假设的行为。 )

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2020-12-17
      • 1970-01-01
      • 2017-09-17
      相关资源
      最近更新 更多