我正在尝试编写一个在响应中传输 JSON 数据的
ApiController
。事情是这样的;
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
。肯定是在返回之前写完吧?我做错了什么?
多亏了这篇文章,我才明白了这一点。事实证明我把事情复杂化了。这是最终的解决方案;
[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;
}