System.Text.Json 方式
services.AddControllersWithViews().AddJsonOptions(options =>
{
// 处理输出时时间转换问题
options.JsonSerializerOptions.Converters.Add(new CustomDateTimeConverter());
});
public class CustomDateTimeConverter : JsonConverter<DateTime>
{
private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
DateTime.Parse(reader.GetString());
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) =>
writer.WriteStringValue(value.ToString(_dateFormat));
}
Newtonsoft.Json 方式
- 引用:Microsoft.AspNetCore.Mvc.NewtonsoftJson
services.AddControllersWithViews().AddNewtonsoftJson(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; });