"Cannot convert value to NodaTime.LocalDateTime"



我正在使用。Net Core 3.1作为我的框架。

我在启动时有这样的设置:

using NodaTime;
using NodaTime.Serialization.SystemTextJson;
services.AddControllers()
.AddJsonOptions(options =>
{
var settings = options.JsonSerializerOptions;
settings.AllowTrailingCommas = false;
settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
settings.WithIsoDateIntervalConverter();
settings.WithIsoIntervalConverter();
});

这是我的API模型:

public class CreateDto
{
public int Status { get; set; }
public Guid ApprovedBy { get; set; }
public LocalDateTime DateFrom { get; set; }
public LocalDateTime DateTo { get; set; }
}

这是我的控制器:

[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateDto createEntity)
{
var createdEntity = await _service.Create(createEntity);
return Ok(createdEntity);
}

每次我将Postman与这个JSON Body一起使用时:

{
"Status": 1,
"ApprovedBy": "970a50c5-ae21-4f41-bea9-691f8c60224c",
"DateFrom": "2020-04-01T00:00:00.000Z",
"DateTo": "2020-04-05T23:59:59.000Z"
}

我总是收到这样的错误:

{
"errors": {
"DateTo": [
"Cannot convert value to NodaTime.LocalDateTime"
],
"DateFrom": [
"Cannot convert value to NodaTime.LocalDateTime"
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|4a836dd3-4ce779bc5503ac63."
}

问题:我的启动配置中缺少什么吗?如果没有,我该怎么做才能修复此错误?

您的JSON不表示LocalDateTime值,而是表示Instant(或OffsetDateTime(值,因为末尾有"Z"。

所以你的选择是:

  • 将模型中的类型更改为InstantOffsetDateTime
  • 更改您发送的数据-只需删除每个字符串末尾的"Z">

最新更新