C# 将Json数据流式传输到ASP.NET ApicController

C# 将Json数据流式传输到ASP.NET ApicController,c#,asp.net,asp.net-apicontroller,C#,Asp.net,Asp.net Apicontroller,我正在尝试编写一个ApiController,在响应中传输JSON数据。事情是这样的 公共类MyController:ApiController { 我是一个文档作者; 公共MyControllerIDocumentWriter { _作家=作家; } [HttpGet] 公共异步任务获取 { var response=Request.CreateResponseHttpStatusCode.OK; 使用var stream=newmemoryStream { response.Content=

我正在尝试编写一个ApiController,在响应中传输JSON数据。事情是这样的

公共类MyController:ApiController { 我是一个文档作者; 公共MyControllerIDocumentWriter { _作家=作家; } [HttpGet] 公共异步任务获取 { var response=Request.CreateResponseHttpStatusCode.OK; 使用var stream=newmemoryStream { response.Content=newstreamcontentstream; wait_writer.WriteAsyncstream; response.Content.Headers.ContentType=新的MediaTypeHeaderValueapplication/json; response.Content.Headers.ContentLength=stream.Length; } 返回响应; } }
IDocumentWriter接受流并将JSON数据写入其中。调用Get失败,出现System.Threading.Tasks.TaskCanceledException,我不理解,因为我正在等待WriteAsync。它肯定会在回来之前写完吗?我做错了什么?

多亏了你,我才明白。原来我把事情复杂化了。这是最终的解决方案

[HttpGet] 公共异步任务获取 { var response=Request.CreateResponseHttpStatusCode.OK; response.Content=新的PushStreamContentasync流,内容,上下文=> { wait_writer.WriteAsyncstream; 关闭;; },application/json; 返回响应; }
您正在使用的示例并没有真正利用流媒体,因为MemoryStream表示内存中固定大小的缓冲区—它并不比使用ByteArrayContent好多少。您应该直接写入HttpContext.Response输出流。请发布TaskCanceledException的完整堆栈跟踪,包括最底部的[Async]部分,以及任何InnerException对象及其对应的完整堆栈-traces@Dai你完全正确。这就是解决办法。我只是不知道如何使用StreamContent直接写入输出流,因为这需要一个流,而不是公开一个流。使用PushStreamContent解决了这个问题。