无法将值转换为NodaTime.Instant



我在后http调用的正文中传递即时日期时遇到了这个问题。

我的API模型:

public class ConfortPlantRequestDTO
{
public Instant instantStartDate { get; set; }
public Instant instantEndDate { get; set; }
public List<string> plants { get; set; } = new List<string>();
}

这是我的控制器:

[HttpPost]
[Route("GetComfortPlant")]
public async Task<ActionResult> GetComfortPlant([FromBody] ConfortPlantRequestDTO requestData)
{
try
{
return Ok(await _confortPlantGraphicsService.getComfortPlantAsync(requestData));
}
catch (Exception ex)
{
CoreLogger.Error($"Exception: {ex}");
return BadRequest(ex.Message);
}
}

JSON正文:

{
"instantStartDate": "2020-10-01T00:00:00.00Z",
"instantEndDate": "2023-05-15T00:00:00.00Z",
"plants": [
1,
2,
3,
4,
5,
10,
397,
22,
404,
45
]
}

错误

{
"errors": {
"instantEndDate": [
"Error converting value 15/05/2023 00:00:00 to type 'NodaTime.Instant'. Path 'instantEndDate', line 3, position 45."
],
"instantStartDate": [
"Error converting value 01/10/2020 00:00:00 to type 'NodaTime.Instant'. Path 'instantStartDate', line 2, position 47."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-28675fabe9fde94c8749f873eb69aac0-01b932d00e8ed149-00"
}

我不明白为什么它不能转换日期,因为它是通过在url中传递参数来完成的,它可以

您必须修复DTO类

using Newtonsoft.Json;
var result=JsonConvert.DeserializeObject<ConfortPlantRequestDTO>(json);

public class ConfortPlantRequestDTO
{
public DateTime instantStartDate { get; set; }
public DateTime instantEndDate { get; set; }
public List<string> plants { get; set; } = new List<string>();
}

我通过在json文件中传递的日期上添加7个零来解决这个问题。

解决方案:

更改表示日期的两个参数:

"instantStartDate": "2020-10-01T00:00:00.00Z",
"instantEndDate": "2023-05-15T00:00:00.00Z",

收件人:

"instantStartDate": "2020-10-01T00:00:00.000000000Z",
"instantEndDate": "2023-05-15T00:00:00.000000000Z",

我在以下位置找到了解决方案:https://nodatime.org/3.0.x/api/NodaTime.Instant.html

最新更新