.NET Core/5 使用自定义 NewtonSoft 转换器反序列化,但模型仍绑定为 null

问题描述

我正在尝试反序列化 .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 转换器返回的对象在绑定过程中被丢弃?

解决方法

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

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