title: Proper way to read and write web api response stream
body: <p>I'm having some trouble with finding the right incantation that will allow me to write to a response stream and then later read the contents in a test. Currently I have this</p>
  
  <pre><code>var res = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
  var ms = new MemoryStream();
  res.Content = new StreamContent(ms);
  using (var sw = new StreamWriter(ms, System.Text.Encoding.UTF8))
  using (var csv = new CsvHelper.CsvWriter(sw))
    csv.WriteRecords(allData.ToList());
  return res;
  </code></pre>
  
  <p>In my test I'm trying to read this response</p>
  
  <pre><code>  var controller = appContainer().Resolve&lt;MyController&gt;();
    var res = (await controller.Get()) as HttpResponseMessage;
    res.ShouldNotEqual(null);
    var csv = await res.Content.ReadAsStringAsync();
  </code></pre>
  
  <p>the last line generates an error</p>
  
  <pre><code>Error while copying content to a stream.
    ----&gt; System.ObjectDisposedException : Cannot access a closed Stream.
  </code></pre>
  
  <p>So there's a couple things here</p>
  
  <ul>
  <li>Why is this error happening and how can I prevent it properly in the test?</li>
  <li>The use of <code>MemoryStream</code> doesn't sit right with me, shouldn't I be able to write directly to the content's stream? Isn't <code>MemoryStream</code> potentially hugely increasing my memory usage?</li>
  </ul>