我正在使用 .NET 8,我注意到请求中的 DateTime 字符串在查询参数和正文中的解析方式不同。
我提出了这个示例请求来显示问题:
POST /api/Save?ValidFrom=2024-01-01T00:00:00+01:00
{
"validFrom":"2024-01-01T00:00:00+01:00"
}
正如您所看到的,查询参数中的日期和正文中的日期是相同的。我使用的是 ISO8601 格式。问题是,现在在控制器方法上,查询参数中的日期被解析为 UTC Kind“31.12.2023 23:00:00”,而正文中的日期被解析为 Local Kind“01.01.2024 00:00:00” .
[HttpPost]
public async Task<ActionResult<InstitutionContributionRecognitionModel>> SaveAsync(DateTime ValidFrom, [FromBody] Model model, CancellationToken cancellationToken)
{
// ValidFrom = 31.12.2023 23:00:00
// model.ValidFrom = 01.01.2024 00:00:00
}
有没有办法在查询参数中使用相同的解析行为?我目前看到的唯一解决方法是在查询参数中使用 DateTimeOffset 并使用 LocalDate。
使用
DateTimeOffset
以便在解析过程中保留时区信息。因此,请更新您的控制器方法以使用 DateTimeOffset
。像这样的东西:
[HttpPost]
public async Task<ActionResult<InstitutionContributionRecognitionModel>> SaveAsync(
DateTimeOffset ValidFrom,
[FromBody] Model model,
CancellationToken cancellationToken)
{
// Both ValidFrom and model.ValidFrom should be the same now.
}
此外,也更新您的模型以使用
DateTimeOffset
。
public class Model
{
public DateTimeOffset ValidFrom { get; set; }
}