ISO UTC DateTime format as default json output format in MVC 6 API response

旧城冷巷雨未停 提交于 2019-12-31 11:32:30

问题


Does anyone know how to configure MVC6's json output to default to a ISO UTC DateTime string format when returning DateTime objects?

In WebApi2 I could set the JsonFormatter SerializerSettings and convert datetimes however i'm a bit stuck with how to do this in MVC6


回答1:


And I just stumbled onto something that helped me figure it out.

Just in case anyone wants to know

In your Startup.ConfigureServices

services.AddMvc().AddJsonOptions(options =>
                {
                    options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                });



回答2:


In case you've migrated to ASP.NET Core 3.0 the code that sf. has posted doesn't work anymore. To spare you some of my headache, here is what you need to do. First create a custom DateTime JSON converter:

public class DateTimeConverter : JsonConverter<DateTime> {
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
        return DateTime.Parse(reader.GetString());
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) {
        string jsonDateTimeFormat = DateTime.SpecifyKind(value, DateTimeKind.Utc)
            .ToString("o", System.Globalization.CultureInfo.InvariantCulture);

        writer.WriteStringValue(jsonDateTimeFormat);
    }
}

And then use it in your Startup.cs as follows:

services.AddControllersWithViews()
    .AddJsonOptions(options => {
        options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
    });

I hope this helps someone.



来源:https://stackoverflow.com/questions/41728737/iso-utc-datetime-format-as-default-json-output-format-in-mvc-6-api-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!