[英]Content.ReadAsAsync always gives null
我在使用Content.ReadAsAsync
閱讀同意時遇到問題。 看看我的代碼。
private HttpResponseMessage _responseMessage;
_responseMessage = UnitTestHelper.Get(string.Format("api/StudentController/Get/?StartDate={0}&EndDate={1}", DateTime.Now, DateTime.Now));
Assert.IsTrue(_responseMessage.IsSuccessStatusCode);
Assert.IsTrue(_responseMessage.Content.ReadAsAsync<List<StudentModel>>().Result.Count > 0);
var auditData = _responseMessage.Content.ReadAsStringAsync().Result;
_responseMessage.Content.ReadAsAsync<List<StudentModel>>().Result;
上面代碼的結果:
它成功地進行了后期調用,得到了結果。
Result.Count 顯示 1。
ReadAsStringAsync 按以下格式顯示數據。
[{\\"User\\":\\"Test\\",\\"Location\\":\\"MyCountry\\",\\"Class\\":\\"Grade1\\",\\"Time\\":\\"2016-07-06T07:26:11.183\\",\\"SchoolName\\":\\"ABC School System\\"}]
最后一行給出空值。 我期待這里的清單。
我的問題。
以下代碼行始終顯示 null。 而我期待有清單。
_responseMessage.Content.ReadAsAsync<List<StudentModel>>().Result;
為什么? 這里有什么問題?
問題是您要兩次調用_responseMessage.Content.ReadAsAsync<List<StudentModel>>()
。 您應該將結果存儲在某個變量中,然后使用它
var result = _responseMessage.Content.ReadAsAsync<List<StudentModel>>().Result;
Assert.IsTrue(result.Count > 0);
//do whatever needed with result
另外,您最好利用async/await
而不是調用.Result
更具體地說, ReadAsAsync<T>
使用內部HttpContent.ReadAsStreamAsync
緩存內存流,並且一旦讀取, Position
停留在流的末尾。
您必須將 NewtonSoft.json.dll 更新到最新版本。 這應該有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.