[英]C# asp.net core webapi throwing "The JSON value could not be converted to System.Nullable`1[System.DateTime]
I have a asp.net core webapi with class property DateTime?我有一个带有 class 属性 DateTime 的 asp.net 核心 webapi? DateofBirth.
出生日期。 The front end is sending the date of birth as a string in the format.
前端将出生日期作为格式的字符串发送。 "MM/dd/yyyy".
“MM/dd/yyyy”。 I dont want to change the C# property with string type.
我不想用字符串类型更改 C# 属性。 Is there a better solution to handle this?
有没有更好的解决方案来处理这个问题?
public class Entity
{
public Guid Id { get; set; }
[Required(ErrorMessage = "FirstName must be supplied")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Surname must be supplied")]
public string Surname { get; set; }
public DateTime? DateOfBirth { get; set; }
}
POSTMAN request: POSTMAN 请求:
{
"dateOfBirth": "07/07/2020",
"surname": "Martin",
"id": "ae8d7edf-23b6-498b-865d-9840ce401b19",
"firstName": "Robert",
}
Error:错误:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|4dd4b26-4340be36ab0c62cc.",
"errors": {
"$.dateOfBirth": [
"The JSON value could not be converted to System.Nullable`1[System.DateTime]. Path: $.dateOfBirth | LineNumber: 2 | BytePositionInLine: 31."
]
}
}
The error is because by default System.Text.Json
library parses the value from JSON according to the ISO 8601:-2019
extended profile.该错误是因为默认情况下
System.Text.Json
库根据ISO 8601:-2019
扩展配置文件解析 JSON 中的值。
Two ways to handle it:两种处理方式:
MM/DD/YYYY
to YYYY-MM-DD
.MM/DD/YYYY
更改为YYYY-MM-DD
。 (This is ISO 8601 compliant)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.