正在从.Net Core 2.1 Web API中的JSON DateTime响应中删除时间组件



我有一个ASP.Net Core 2.1 Web API,它在一个控制器操作中返回一个DateTime。JSON如下所示:

1965-02-03T00:00:00

我想这是ISO 8601…

由于这实际上是一个出生日期,我希望它不包含时间成分。Net没有只包含日期的数据类型(就像我的底层MySQL数据库一样(,所以我必须使用DateTime类型。有没有任何方法可以将输出到消费客户端的JSON数据格式化为YYYY-MM-DD?

控制器的操作非常简单:

// GET: api/Persons
[HttpGet]
public IEnumerable<Person> GetPerson()
{
return _context.Persons;
}

Person模型也很简单:

public partial class Person
{
public int Id { get; set; }
public string Forenames { get; set; }
public string Surname { get; set; }
public string Title { get; set; }
public string IdNumber { get; set; }
public DateTime? DateOfBirth { get; set; }
}

要在Asp.Net Core中配置Json Serialize,可以将AddJsonOptionsJsonSerializerSettings一起使用。

//
// Summary:
//     Gets or sets how System.DateTime and System.DateTimeOffset values are formatted
//     when writing JSON text, and the expected date format when reading JSON text.
//     The default value is "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK".
public string DateFormatString { get; set; }

最新更新