不支持无参数构造函数的引用类型的反序列化

我有这个API

 public actionResult AddDocument([FromBody]AddDocumentRequestModel documentRequestModel)
        {
            AddDocumentStatus documentState = _documentService.AddDocument(documentRequestModel,DocumentType.OutgoingPosShipment);
            if (documentState.IsSuccess)
                return Ok();

            return BadRequest();
        }

这是我的请求模型

    public class AddDocumentRequestModel
    {
        public AddDocumentRequestModel(int partnerId,List<ProductRequestModel> products)
        {
            PartnerId = partnerId;
            Products = products;
        }

        [Range(1,int.MaxValue,ErrorMessage = "Value for {0} must be between {1} and {2}.")]
        public int PartnerId { get; private set; }

        [Required,MustHaveoneElement(ErrorMessage = "At least one product is required")]
        public List<ProductRequestModel> Products { get; private set; }
    }

所以当我尝试使用此主体来访问API

{
        "partnerId": 101,"products": [{
            "productId": 100,"unitOfMeasureId": 102,"quantity":5
        }
     ]
}

这是请求:System.NotSupportedException:不支持无参数构造函数的引用类型的反序列化。键入“ Alati.Commerce.Sync.Api.Controllers.AddDocumentRequestModel”

我不需要无参数的构造函数,因为它不读取主体参数。还有其他反序列化的方法吗?

wujianlin1984 回答:不支持无参数构造函数的引用类型的反序列化

您可以实现所需的结果。您需要切换到NewtonsoftJson序列化(来自软件包Microsoft.AspNetCore.Mvc.NewtonsoftJson)

在Startup.cs中使用ConfigureServices方法调用此函数:

    services.AddControllers().AddNewtonsoftJson();

此后,您的构造函数将被反序列化调用。

其他信息:我正在使用ASP Net Core 3.1

后来的编辑:我想提供更多有关此的信息,因为这似乎也可以使用System.Text.Json来实现,尽管自定义实现是必需的。来自jawa的回答指出,Deserializing to immutable classes and structs可以通过System.Text.Json来实现,方法是创建一个自定义转换器(从JsonConverter继承)并将其注册到转换器集合(JsonSerializerOptions.Converters),如下所示:

   public class ImmutablePointConverter : JsonConverter<ImmutablePoint>
   {
   ...
   }

然后...

   var serializeOptions = new JsonSerializerOptions();
   serializeOptions.Converters.Add(new ImmutablePointConverter());
   serializeOptions.WriteIndented = true;
,

使用System.Text.Json仍有一些限制-在这里看看:https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#table-of-differences-between-newtonsoftjson-and-systemtextjson 目前尚不支持在不使用无参数构造函数的情况下使用参数化构造函数进行反序列化(但这已在他们的计划中)。您可以实现自定义JsonConverter(如本例中的https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#deserialize-to-immutable-classes-and-structs)或-如上述建议的Adrian Nasul:使用Newtonsoft.Json,然后可以使用[JsonConstructor]属性

本文链接:https://www.f2er.com/2968967.html

大家都在问