Returning a JSON stream from an ApiController

自作多情 提交于 2020-01-14 13:54:11

问题


I've got a large JSON Object which I need to return from an MVC ApiController.

I can't simply return the JSON Object as the internal serializer barfs on the serialized contents being too long.

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.

What I want to do is use the Newtonsoft JSON Serializer to write to the response stream directly.

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

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?

Even if I strip out all the Using blocks and just leave everything for the GC as here:

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

I get a 0-byte response instead. Can someone please point me in the right direction?


回答1:


Have you tried checking timeout settings in web.config/machine.config? Maybe IIS decides that it's taking too long to get Response.Content.

Anyhow, you should check this issue out with Failed Requests Using Tracing - that should point you in the right direction.




回答2:


It turns out this was a silly mistake on my part... I wasn't flushing the writer and resetting the stream position...

JsonWriter.Flush()
MemoryStream.Seek(0, StreamPosition.Beginning)

Solved the problem



来源:https://stackoverflow.com/questions/13268237/returning-a-json-stream-from-an-apicontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!