将 Json 数据流式传输到 ASP.NET ApiController
Streaming Json data to ASP.NET ApiController
我正在尝试编写一个 ApiController
在响应中流式传输 JSON 数据。它是这样的;
public class MyController : ApiController
{
IDocumentWriter _writer;
public MyController(IDocumentWriter writer)
{
_writer = writer;
}
[HttpGet]
public async Task<HttpResponseMessage> Get()
{
var response = Request.CreateResponse(HttpStatusCode.OK);
using (var stream = new MemoryStream())
{
response.Content = new StreamContent(stream);
await _writer.WriteAsync(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Content.Headers.ContentLength = stream.Length;
}
return response;
}
}
IDocumentWriter
接受流并将 JSON 数据写入其中。对 Get
的调用失败并显示 System.Threading.Tasks.TaskCanceledException
,我不明白,因为我正在等待 WriteAsync
。确定它在返回之前写完了吗?我做错了什么?
感谢 this post,我弄明白了。原来我把事情复杂化了。这是最终的解决方案;
[HttpGet]
public async Task<HttpResponseMessage> Get()
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new PushStreamContent(async (stream, content, context) =>
{
await _writer.WriteAsync(stream);
stream.Close();
}, "application/json");
return response;
}
我正在尝试编写一个 ApiController
在响应中流式传输 JSON 数据。它是这样的;
public class MyController : ApiController
{
IDocumentWriter _writer;
public MyController(IDocumentWriter writer)
{
_writer = writer;
}
[HttpGet]
public async Task<HttpResponseMessage> Get()
{
var response = Request.CreateResponse(HttpStatusCode.OK);
using (var stream = new MemoryStream())
{
response.Content = new StreamContent(stream);
await _writer.WriteAsync(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Content.Headers.ContentLength = stream.Length;
}
return response;
}
}
IDocumentWriter
接受流并将 JSON 数据写入其中。对 Get
的调用失败并显示 System.Threading.Tasks.TaskCanceledException
,我不明白,因为我正在等待 WriteAsync
。确定它在返回之前写完了吗?我做错了什么?
感谢 this post,我弄明白了。原来我把事情复杂化了。这是最终的解决方案;
[HttpGet]
public async Task<HttpResponseMessage> Get()
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new PushStreamContent(async (stream, content, context) =>
{
await _writer.WriteAsync(stream);
stream.Close();
}, "application/json");
return response;
}