Home > Software engineering >  Blazor HttpClient.GetFromJsonAsync() not working as expected
Blazor HttpClient.GetFromJsonAsync() not working as expected

Time:12-21

When using HttpClient.GetFromJsonAsync() or Content.ReadFromJsonAsync<T>() some properties are not parsed correctly.

Chrome debugger parsed the UserSsid property correctly:

enter image description here

But the HttpClient did not:

enter image description here

Blazor-Client code

async Task WaitForExport(string location)
{
    while (await periodicTimer.WaitForNextTickAsync())
    {
        var response = await Http.GetAsync(location, HttpCompletionOption.ResponseContentRead);
        if (response != null && response.IsSuccessStatusCode)
        {
            var exportStatus = await response.Content.ReadFromJsonAsync<ExportStatusModel>();
            if (exportStatus != null)
            {
                return;
            }
        }
    }
}

Controller

[HttpGet("export-status")]
public async Task<ActionResult<ExportStatusModel>> GetExportStatus(Guid guid)
{
    var model = await _exportRequestRepository.GetExportStatus(guid);
    if (model == null)
        return NotFound();

    return Ok(model);
}

Model

public class ExportStatusModel
{
    public Guid Guid { get; set; }
    public int Status { get; set; }
    public string UserSsid { get; set; } = string.Empty;
    public int DocumentId { get; set; } = -1;
}

I already tried reading the Content as string first to parse it afterwards but this returned a hex string instead of the raw json. Converting this hex string to ascii failed in blazor wasm. In a console application it worked however.

I also noticed that the Content-Length header was missing in the response. Maybe this breaks the json serializer?

CodePudding user response:

The string is in hex:

53 == 'S' and 2D == '-'

You could convert it to a normal string with at least:

string newssid = "";

for (int i = 0; i < ssid.Count(); i =2)
{
  newssid  = ""   (char)Convert.ToByte(ssid.Substring(i, 2), 16);
}

I dont know why its in hex though. Maybe you turned on "show as hexadecimal" in Visual studio.

Right click on the Field and check if hexadecimal display is checked!

  • Related