[英]ASP.NET Web API: DateTime binding not working in json body
For DateTime
type, if I have a DateTime
property inside a class then I try to model bind that class with HTTP post json body, the DateTime
property does not get bound, how so? 对于DateTime
类型,如果我在类内有DateTime
属性,则尝试使用HTTP post json主体对该类进行模型绑定,但DateTime
属性不会被绑定,怎么办? But if I use parameter binding, it's working fine. 但是,如果我使用参数绑定,则可以正常工作。 So below code works 所以下面的代码有效
[Route("v1/taxiqi")]
[HttpPost]
public object UpdateTaxiQI(string status, DateTime updateTime)
{
...
}
But not for below code 但不适用于以下代码
[Route("v1/taxiqi")]
[HttpPost]
public object UpdateTaxiQI(TaxiQI taxiQI)
{
...
}
public class TaxiQI
{
public string Status;
public DateTime UpdateTime;
}
I am using the latest ASP.NET Web API. 我正在使用最新的ASP.NET Web API。 Fields are working as it is working on my other API, besides, Status field is successfully bound. 字段与我的其他API一样有效,此外,状态字段已成功绑定。 And I already tried properties, same result. 我已经尝试过属性,结果相同。
Sorry, I found out the root cause, it is caused by our code base is using a custom DateTimeConverter
for JSON.NET
and it expects a JavaScript style ticks instead of a date string 抱歉,我发现了根本原因,这是由于我们的代码库针对JSON.NET
使用了自定义DateTimeConverter
JSON.NET
并且它期望JavaScript样式号而不是日期字符串
Your TaxiQI
class is incorrect. 您的TaxiQI
类别不正确。
The JSON works with public properties not public fields. JSON使用公共属性而非公共字段。 Change your class to this: 将您的班级更改为此:
public class TaxiQI
{
public string Status { get; set; }
public DateTime UpdateTime { get; set; }
}
In addition to Svek's answer, it may be wiser to use a Nullable<DateTime>
or DateTime?
除了Svek的答案,使用Nullable<DateTime>
或DateTime?
可能更明智DateTime?
instead. 代替。 Null values are an intrinsic possibility whenever you deserialize data. 当您反序列化数据时,空值是一种内在的可能性。
我发现了根本原因,很糟糕,这是由于我们的代码库对JSON.NET使用了自定义DateTimeConverter引起的,并且它期望使用JavaScript样式标记而不是日期字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.