简体   繁体   English

Content.ReadAsAsync 总是给 null

[英]Content.ReadAsAsync always gives null

I am facing issue in reading consents using Content.ReadAsAsync .我在使用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. Result.Count 显示 1。

  • ReadAsStringAsync shows data in the following format. ReadAsStringAsync 按以下格式显示数据。

     [{\\"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.以下代码行始终显示 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. 问题是您要两次调用_responseMessage.Content.ReadAsAsync<List<StudentModel>>() 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 另外,您最好利用async/await而不是调用.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. 更具体地说, ReadAsAsync<T>使用内部HttpContent.ReadAsStreamAsync缓存内存流,并且一旦读取, Position停留在流的末尾。

You have to update NewtonSoft.json.dll to the latest.您必须将 NewtonSoft.json.dll 更新到最新版本。 This should work.这应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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