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\":\"[email protected]\",\"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.
CodePudding user response:
Your User class appears not to match the response json, you can either create the class structure that matches the response like this
public class RouteValues
{
public string id { get; set; }
}
public class Value //your user class
{
public string uid { get; set; }
public string email { get; set; }
public bool active { get; set; }
public DateTime created { get; set; }
public DateTime updated { get; set; }
}
public class Response
{
public string actionName { get; set; }
public RouteValues routeValues { get; set; }
public Value value { get; set; }
public List<object> formatters { get; set; }
public List<object> contentTypes { get; set; }
public int statusCode { get; set; }
}
and deserialize to the Response class and access the value object which is the equivalent to your user object or deserialize by specifying the key which does contain your user object, that being the value key.
CodePudding user response:
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.