我正在尝试解析来自 ASP.NET 核心Web API的响应。我能够成功地将响应 JSON 解析为 C# 对象,但是当解析的 C# 对象返回到 ViewModel 时,应用程序崩溃而不会引发任何错误。
在视图中模型
ApiResponse response = await _apiManager.GetAsync<ApiResponse>("authentication/GetUserById/1");
响应 JSON:
{
"result": {
"id": 1,
"userType": 1,
"firstName": “FirstName”,
"middleName": null,
"lastName": “LastName”,
},
"httpStatusCode": 200,
"httpStatusDescription": "200OkResponse",
"success": true,
"message": "hello"
}
HttpClient GetAsync() 方法:
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;
}
应用崩溃(调试器停止,没有任何错误)在"return t"语句。在这里,_httpClient是使用 DI 的 HttpClient 的单例对象。
模型是 ApiResponse 对象
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();
}
有两个问题: 1. 执行以下语句时,应用程序崩溃,调试器停止,而不会引发任何错误。
HttpResponseMessage httpResponse = await _httpClient.GetAsync(endpoint).ConfigureAwait(false);
但是当 GetAsync() 被调用时。GetAwaiter()。GetResult(),网络调用成功下达。我不明白为什么配置等待(假)失败。
HttpResponseMessage httpResponse = _httpClient.GetAsync(endpoint).GetAwaiter().GetResult();
为什么以下调用失败并且应用程序崩溃?如何将解析的 C# 对象返回到调用代码?
返回 JsonConvert.DeserializeObject(serialized);
请指教。
试试这个
try
{
var result = await httpClient.GetAsync(endpoint);
var response = await result.Content.ReadAsStringAsync();
data = JsonConvert.DeserializeObject<TResult>(response);
}
catch (Exception exp)
{
Console.Write(exp.InnerMessage);
}
确保您已安装 Newtonsoft.json