【发布时间】:2019-12-05 15:31:19
【问题描述】:
我有这个 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; }
}
所以当我试图用这个 body 访问 API 时
{
"partnerId": 101,
"products": [{
"productId": 100,
"unitOfMeasureId": 102,
"quantity":5
}
]
}
这是请求:System.NotSupportedException:不支持没有无参数构造函数的引用类型的反序列化。输入“Alati.Commerce.Sync.Api.Controllers.AddDocumentRequestModel”
我不需要无参构造函数,因为它不读取body参数。有没有其他反序列化的方法?
【问题讨论】:
-
一些 IDE(例如 Rider)会建议您将用于序列化的类转换为抽象类。删除 abstract 关键字(改用具体类),它将解决此异常的许多其他问题,而不是 OP 提到的。
-
应该从 .NET 5.0 开始工作。见github.com/dotnet/runtime/issues/41313
-
在 .NET 6 中,我们在处理字典键中的 System.Uri 时仍然需要使用 Newtonsoft.Json。 docs.microsoft.com/en-us/dotnet/standard/serialization/…
标签: serialization json-deserialization .net-core-3.0