.Net Core NewtonsoftJson DateTimeZoneHandling setting not working

Viewed 946

I started porting our .Net Framework WebAPIs to .Net Core 5 at work. I noticed that dates being returned in the SPA were off and upon further investigation I saw that after the objects were serialized that the dates were being set as UTC.

I've found that I can get it to work at serialization/deserialization by adding the option as an argument, but it seems like this should be able to be done globally instead of each time the serializer runs.

I've tried adding the following in the WebAPI Startup.cs to change how the dates were being returned but it doesn't seem to work in the startup:

services.AddControllers().AddNewtonsoftJson(o => o.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Unspecified);

2 Answers

Add this:

services.AddControllers().AddNewtonsoftJson();

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{

    DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
};

I had to convert to UTC format(DateTimeZoneHandling.Utc) and the above ways(DateTimeZoneHandling) did not work for me. Finally below worked:

.AddNewtonsoftJson(opts =>
            {    
                opts.SerializerSettings.Converters.Add(new IsoDateTimeConverter
                    {
                        DateTimeStyles = DateTimeStyles.AdjustToUniversal
                    });
            }

I hope this helps to people who are looking to convert date time format to UTC globally.

Related