为何C#中ReadAsAsync<TResponse>返回null,JsonConvert反序列化却正常?
问题描述
我编写了如下C#代码:
private class TResponse { public bool IsSuccessful { get; set; } public string ErrorCode { get; set; } public string ErrorMessage { get; set; } } var response = client.PostAsJsonAsync(methodName, data).Result; TResponse result = default(TResponse); var responseString = response.Content.ReadAsStringAsync().Result; if (responseString.CompareTo("null") != 0) result = response.Content.ReadAsAsync<TResponse>().Result;
这段代码中result始终为null,但改用以下方式却能得到有效值:
var responseContent = response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject<TResponse>(responseContent.Result.ToString());
我曾将第一种方法用于多个实体类型均正常,但对TResponse类却无效。已知response.Content.ReadAsStringAsync()返回的内容为:"{\"IsSuccessful\":false,\"ErrorCode\":\"8\",\"ErrorMessage\":\"XXXXXXxxxxssssss.\"}"
请问第一种代码为何无法正常工作?
问题原因及解决方法
- HttpContent响应流只能被读取一次:你先调用
response.Content.ReadAsStringAsync(),已经把响应流的指针移动到了末尾,后续再调用response.Content.ReadAsAsync<TResponse>()时,流里已经没有可读取的内容,自然反序列化得到null。而第二种方法只读取了一次响应内容,之后直接用JsonConvert反序列化这段字符串,所以能正常拿到结果。 - 你之前用第一种方法对其他实体类型有效,大概率是那些场景里没有提前调用
ReadAsStringAsync()读取响应流,或者遇到了支持重复读取的特殊HttpContent实现(但默认的StreamContent不支持重复读取)。
修正后的代码示例
只读取一次响应内容再反序列化:
var response = client.PostAsJsonAsync(methodName, data).Result; TResponse result = default(TResponse); var responseString = response.Content.ReadAsStringAsync().Result; if (responseString.CompareTo("null") != 0) result = JsonConvert.DeserializeObject<TResponse>(responseString);
或者不提前读取字符串,直接用ReadAsAsync:
var response = client.PostAsJsonAsync(methodName, data).Result; TResponse result = default(TResponse); if (response.IsSuccessStatusCode) { result = response.Content.ReadAsAsync<TResponse>().Result; }
内容的提问来源于stack exchange,提问作者Curious Developer
相关产品推荐
相关产品推荐

