Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft.AspNetCore.Odata configure datetime serialization to use Utc or omit Timezone

I'm using Microsoft.AspNetCore.Odata 7.3 in Asp.net Web Api Core 3.1 project.

It turns out that the lib adds TimeZone of the server to DateTimes from Ef output.

Ef itself returns data with DateTimeKind.Unspecified.

So I expected the odata lib just to omit the TimeZone shift because webApi services behave this way.

The question is how to make odata not to add TimeZone of the server or return everything in utc(Z-format).

Tried to set it via NewtonSoft serializerSettings, but it doesn't work for OData endpoints

services.AddOData();

services.AddMvc(options => {options.EnableEndpointRouting = false;});

services
  .AddControllers()
  .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                });

Thanks for help!

Upd: Setting DateTimeKind to Utc on Ef level(via ValueConverters) allows server to convert datetime correctly to local. But still the datetime is returned not in Z-format but with local TimeZone of server.

like image 206
Dan Ko Avatar asked May 07 '20 08:05

Dan Ko


1 Answers

I have a similar setup (also treated timestamp as UTC on EF layer) and ran into the same issue.

In my case I was able to fix it with the following extension method: https://docs.microsoft.com/en-us/previous-versions/aspnet/mt135699(v=vs.118)?redirectedfrom=MSDN

Example (Startup.cs)

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            if (odataRoutePrefix != null && edmModel != null)
            {
                endpoints.EnableDependencyInjection();
                endpoints.Filter().OrderBy().MaxTop(100).Count().Select();
                endpoints.MapODataRoute("odata", odataRoutePrefix, edmModel);
                endpoints.SetTimeZoneInfo(TimeZoneInfo.Utc);
            }
        });
like image 121
bort Avatar answered Oct 24 '22 08:10

bort