Asp.net web api 如何在.NETWebAPI中将DateTime对象作为json传递
我有一个包含日期时间类型的模型:Asp.net web api 如何在.NETWebAPI中将DateTime对象作为json传递,asp.net-web-api,asp.net-core,Asp.net Web Api,Asp.net Core,我有一个包含日期时间类型的模型: public class ToDo { public int id { get; set; } public int parentId { get; set; } public string note { get; set; } public DateTime due { get; set; } public ToDo(int id, int parentId, st
public class ToDo
{
public int id { get; set; }
public int parentId { get; set; }
public string note { get; set; }
public DateTime due { get; set; }
public ToDo(int id, int parentId, string note, DateTime due)
{
this.id = id;
this.parentId = parentId;
this.note = note;
this.due = due;
}
}
我已经为这个类创建了一个控制器,通过api发送我的post请求。但我不知道如何将DateTime类型绑定到json,我尝试了一个具有以下主体的请求,但没有成功:
{"parentId":1,"note":"hello world","due":{"year":2017,"month": 11,"day":25}}
我应该如何发布日期时间类型?显然,您可以这样做:
{"due": "2017-11-01T00:00:00"}
这实际上是一个简单的问题,但如果您想确保如何对未知对象类型格式发出正确的post请求,最好发送一个主体为空的对象以查看默认值。对于
DateTime
Type属性,您需要传递可以转换为DateTime
类型的字符串
对于{“年”:2017,“月”:11,“日”:25}
,它是对象而不是字符串,它将无法转换为日期时间
对于可以通过Convert.ToDateTime
和DateTime.Parse
转换为DateTime
的任何内容
因此,{“parentId”:1,“note”:“hello world”,“due”:“05/05/2005”}
和{“parentId”:1,“note”:“hello world”,“due”:“2018-05-10”}
都可以工作,您可以使用所需的日期时间字符串进行测试