Search code examples
c#jsonasp.net-core-mvcasp.net-core-webapidotnet-httpclient

Response Content not Hydrating Object


I'm calling an API in the Controller of a MVC Core app as follows:

HttpContent httpContent = new StringContent(string.Empty, Encoding.UTF8, "text/plain");
HttpResponseMessage response = await client.PostAsync("api/users", httpContent);

if (response.IsSuccessStatusCode) {
    User userJson = await response.Content.ReadFromJsonAsync<User>();                
    string responseContent = await response.Content.ReadAsStringAsync();

The value of responseContent is:

"{
   \"actionName\":\"GetUser\",
   \"routeValues\":{\"id\":\"30131055-9ff0-472f-a147-69e76f7aac77\"},
   \"value\":{\"uid\":\"a36065bd-9d88-4ea3-f04d-08d98cfa8b83\",
   \"email\":\"example@example.org\",
   \"active\":true,\"created\":\"2021-10-12T19:49:16.0054897Z\",
   \"updated\":\"2021-10-12T19:49:16.0054899Z\"},\"formatters\":[],
   \"contentTypes\":[],
   \"statusCode\":201
}"

I wasn't expecting this type of formatted content, I was expecting JSON, but I can see my the values for my User object in the "value" section.

My User object properties of uid, email, active, created, and updated are all public properties with get/set methods.

So I can see that my data is there, but when I try to deserialize the response to the User object I just see the default values after instantiation.

I feel like I'm missing something simple.


Solution

  • Christian Franco noticed that the items in the object being return matched CreatedAtActionResult which the API I was calling was returning instead of the values I expected. This explains the odd behavior I was seeing.