从ApiController返回一个JSON流 [英] Returning a JSON stream from an ApiController

查看:1271
本文介绍了从ApiController返回一个JSON流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的的JSON对象,我需要从一个MVC ApiController回来。

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

我不能简单地返回JSON对象的序列化内容的内部串行barfs太长​​。

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

我不想序列化到字符串,然后返回字符串,我们可以处理数据的5-6MB和看起来像的内存没有目的的浪费。

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.

我想要做的就是使用Newtonsoft JSON序列写入直接响应流。

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?

即使我去掉所有的使用块和刚刚离开一切为了GC如下:

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

我得到一个0字节的响应来代替。可有人请点我朝着正确的方向?

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

推荐答案

原来,这是我的一个愚蠢的错误......我不冲水的作家和重置流位置...

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)

问题解决了

这篇关于从ApiController返回一个JSON流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆