Home > Software design >  Correctly serialize and deserialize DateTime .NET Web Api/Blazor
Correctly serialize and deserialize DateTime .NET Web Api/Blazor

Time:01-17

I want to display the server time in my Blazor app. What I currently do is:

Controller:

[HttpGet]
        public Task<DtoValue<DateTime>> GetServerLocalTime() 
             => Task.FromResult(new DtoValue<DateTime>(DateTime.Now));

with

public class DtoValue<T>
{
    public DtoValue()
    {
    }

    public DtoValue(T? value)
    {
        Value = value;
    }

    public T? Value;
}

in my Program.cs I added Newtonsoft:

builder.Services.AddControllers()
    .AddNewtonsoftJson();

The returned value of my WebApi looks like this:

{
  "value": "2023-01-16T23:13:53.0037535 01:00"
}

But when I try to deserialize it in my Blazor app:

var dtoTimeValue = await HttpClient.GetFromJsonAsync<DtoValue<DateTime>>("api/Hello/GetServerLocalTime").ConfigureAwait(false);

My dtoTimeValue is the DateTime default value 1/1/0001 12:00:00 AM.

When I manually deserialize the result with NewtonSoft.Json everything is working as expected:

var result = await HttpClient.GetAsync("api/Hello/GetServerLocalTime").ConfigureAwait(false);
var resultString = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
var dtoTimeValue = JsonConvert.DeserializeObject<DtoValue<DateTime>>(resultString);

Why is my Blazor app not able to deserialize the DateTime?

CodePudding user response:

  1. You only add NewtonSoft to your Server. (No need)
  2. Your DTO is using a field not a property.

I don't know why your using .ConfigureAwait(false) (no need)

I would recommend using DateTimeOffset not DateTime.

public class DtoValue<T>
{
    public DtoValue()
    {
    }

    public DtoValue(T? value)
    {
        Value = value;
    }

    public T? Value { get; set; }
}
[ApiController]
[Route("api/[controller]")]
public class Hello : ControllerBase
{
    [HttpGet]
    public Task<DtoValue<DateTime>> GetServerLocalTime()
        => Task.FromResult(new DtoValue<DateTime>(DateTime.Now));
}
serverDate = await Http.GetFromJsonAsync<DtoValue<DateTime>>("api/Hello");
  • Related