Home > OS >  ResponseStream from API results in empty values on deserializing
ResponseStream from API results in empty values on deserializing

Time:05-10

Returning data from my API and deserializing it in the client controller, the content seems to empty. I've verified that the API is returning valid data, and it the "count" in the response is accurate. However, the data when serialized is seems not be initialized.

Not quite sure where to look for what's causing the issue. My best theory is that the data is being deserialized before it's materialized due to the async, but that doesn't explain why the count is correct (2 records).

public async Task<IActionResult> Index()
{
  var httpClient = _httpClientFactory.CreateClient("APIClient");

  var request = new HttpRequestMessage(HttpMethod.Get, "/api/AppUsers");
        
  var response = await httpClient.SendAsync(request).ConfigureAwait(false);

  if (response.IsSuccessStatusCode)
  { 
    using (var responseStream = await response.Content.ReadAsStreamAsync())        
    {
      var users = await JsonSerializer.DeserializeAsync<IList<AppUser>>(responseStream);

      return View(new IndexViewModel(users));
    }
  }
  else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized ||
          response.StatusCode == System.Net.HttpStatusCode.Forbidden) 
  {
    return RedirectToAction("AccessDenied", "Authorization");
  }
  throw new Exception("Problem accessing the API");
  
}

API Method which is called

[HttpGet]
public IActionResult GetAppUsers()
{
  var users = _appUserService.ListAppUsers();
  return Ok(users);
}

enter image description here

Calling the API Method directly shows the 2 rows returned as expected enter image description here

After some debugging, I noticed that the json structure returned from the API is having first letter in property name as lowercase, but the AppUser class have first letter UpperCase. Not sure why this happens, but that's the reason why the deserialization fails.

CodePudding user response:

Try to deserialize to List instead to IList:

var users = await JsonSerializer.DeserializeAsync<List<AppUser>>(responseStream);

I think that you should remove ConfigureAwait(false) so you can remain in the same synchronizaton context.

For more info check this link: https://devblogs.microsoft.com/dotnet/configureawait-faq/

CodePudding user response:

After noticing the properties changing from upper case to lower case on the JSON object, the solution will be to either force JSON to PascalCase as the default now is camelCase

https://codeopinion.com/asp-net-core-mvc-json-output-camelcase-pascalcase/

or I need to consider the camelCase on deserialization.

This issue stole several hours from my life :/ Hope this post can save some hours for somebody else.

  • Related