I am trying to parse response from ASP.NET Core Web API. I am able to parse the response JSON into C# object successfully but app crashes without throwing any error when the parsed C# object is returned to the ViewModel.
in ViewModel
ApiResponse response = await _apiManager.GetAsync<ApiResponse>("authentication/GetUserById/1");
Response JSON:
{
"result": {
"id": 1,
"userType": 1,
"firstName": “FirstName”,
"middleName": null,
"lastName": “LastName”,
},
"httpStatusCode": 200,
"httpStatusDescription": "200OkResponse",
"success": true,
"message": "hello"
}
HttpClient GetAsync() method:
public async Task<TResult> GetAsync<TResult>(string endpoint)
{
HttpResponseMessage httpResponse = _httpClient.GetAsync(endpoint).GetAwaiter().GetResult();
httpResponse.EnsureSuccessStatusCode();
TResult t = default(TResult);
if (httpResponse.IsSuccessStatusCode)
{
string serialized = await httpResponse.Content.ReadAsStringAsync();
t = JsonConvert.DeserializeObject<TResult>(serialized);
}
return t;
}
App crashes (debugger stops without any error) at "return t" statement. Here, _httpClient is a singleton object of HttpClient using DI.
TResult model is ApiResponse object
public class User
{
[JsonProperty("id")]
public int UserId { get; set; }
[JsonProperty("userType")]
public int UserType { get; set; }
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("middleName")]
public string MiddleName { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
}
public abstract class ResponseBase
{
[JsonProperty("httpStatusCode")]
public int HttpStatusCode { get; protected set; }
[JsonProperty("httpStatusDescription")]
public string HttpStatusDescription { get; protected set; }
[JsonProperty("success")]
public bool Success { get; protected set; }
[JsonProperty("message")]
public string Message { get; protected set; }
}
public class ApiResponse : ResponseBase
{
[JsonProperty("result")]
public User Result { get; set; } = new User();
}
There are two issues: 1. when the following statement executes, app crashes and debugger stops without throwing any error.
HttpResponseMessage httpResponse = await _httpClient.GetAsync(endpoint).ConfigureAwait(false);
But when GetAsync() is called with .GetAwaiter().GetResult(), network call is placed successfully. I do not understand why ConfigureAwait(false) fails.
HttpResponseMessage httpResponse = _httpClient.GetAsync(endpoint).GetAwaiter().GetResult();
why the following call fails and app crashes? How can I return parsed C# object to the calling code?
return JsonConvert.DeserializeObject(serialized);
Please advise.