title: Returning a JSON stream from an ApiController
body: <p>I've got a <em>large</em> JSON Object which I need to return from an MVC ApiController.</p>
  
  <p>I can't simply return the JSON Object as the internal serializer barfs on the serialized contents being too long.</p>
  
  <p>I don't want to serialize to string and then return the string as we could be dealing 5-6MB of data and that seems like a waste of memory for no purpose.</p>
  
  <p>What I want to do is use the Newtonsoft JSON Serializer to write to the response stream directly.</p>
  
  <pre><code>Dim Ret = Client.Search(Model) ''Get the results object
  Dim Response As New HttpResponseMessage()
  Using MemoryStream As New IO.MemoryStream
      Using StreamWriter As New StreamWriter(MemoryStream)
          Using JsonWriter As JsonWriter = New JsonTextWriter(StreamWriter)
              Dim Serializer As New JsonSerializer
              Serializer.Serialize(JsonWriter, Ret)
          End Using
      End Using
      Response.Content = New StreamContent(MemoryStream)
      Return Response
  End Using
  </code></pre>
  
  <p>Unfortunately, this results in the connection being reset unexpectedly - I'm guessing this is due to the stream being disposed of before it's finished sending the result?</p>
  
  <p>Even if I strip out all the <code>Using</code> blocks and just leave everything for the GC as here:</p>
  
  <pre><code>Dim Ret = Client.Search(Model)
  Dim Response As New HttpResponseMessage()
  Dim MemoryStream As New IO.MemoryStream
  Dim StreamWriter As New StreamWriter(MemoryStream)
  Dim JsonWriter As JsonWriter = New JsonTextWriter(StreamWriter)
  Dim Serializer As New JsonSerializer
  Serializer.Serialize(JsonWriter, Ret)
  Response.Content = New StreamContent(MemoryStream)
  Return Response
  </code></pre>
  
  <p>I get a 0-byte response instead. Can someone please point me in the right direction?</p>