简体   繁体   中英

Content.ReadAsAsync always gives null

I am facing issue in reading consents using Content.ReadAsAsync . Have a look at my code.

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;

Outcome of above code:

  • It successfully make post call, gets the result back.

  • Result.Count shows 1.

  • ReadAsStringAsync shows data in the following format.

     [{\\"User\\":\\"Test\\",\\"Location\\":\\"MyCountry\\",\\"Class\\":\\"Grade1\\",\\"Time\\":\\"2016-07-06T07:26:11.183\\",\\"SchoolName\\":\\"ABC School System\\"}]
  • Last line gives null. I am expecting a list here.

My Problem.

The following line of code always shows null. Whereas I am expecting to have list.

_responseMessage.Content.ReadAsAsync<List<StudentModel>>().Result;

Why? What is wrong here?

The problem is that you're calling _responseMessage.Content.ReadAsAsync<List<StudentModel>>() twice. You should store the result in some variable and then work with it

var result = _responseMessage.Content.ReadAsAsync<List<StudentModel>>().Result;
Assert.IsTrue(result.Count > 0);
//do whatever needed with result

Also you'd better utilize async/await instead of calling .Result


To be more specific ReadAsAsync<T> uses internaly HttpContent.ReadAsStreamAsync which caches memory stream and once it is read Position stays at the end of the stream.

You have to update NewtonSoft.json.dll to the latest. This should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM