使用 Nancy 流式传输 (SqlFile-)Stream

Stream an (SqlFile-)Stream using Nancy

我想知道如何通过我们的 Nancy-API 直接向客户端发送(在我的例子中)SqlFileStream 而无需在内存中加载流。

到目前为止,我已成功传递流,但 Nancy 的 StreamResponse 将源流 (=SqlFileStream) 复制到输出流,这导致大量内存增加。我希望它能将流发送到哪里。

我在 WebApi 中完成了这项工作,其中 WebApi 在 Owin 管道中注册。 没有明显的内存增加,这在我们谈论相当大的流 (>100MB) 时非常好。 但当然,如果可能的话,我宁愿坚持使用一个 API-application-framework。

有什么建议吗?

我想我找到了解决办法。最后做起来也不是太难。

我创建了一个自定义 Nancy.Response => FlushingStreamResponse。 将流和 mimetype 传递给它,当这是我们的 GET 结果时,会立即流式传输到客户端。

public class FlushingStreamResponse : Response
{
    public FlushingStreamResponse(Stream sourceStream, string mimeType)
    {
        Contents = (stream) =>
        {
            var buffer = new byte[16 * 1024];
            int read;
            while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                stream.Write(buffer, 0, read);
                stream.Flush();
            }
            sourceStream.Dispose();
        };

        StatusCode = HttpStatusCode.OK;
        ContentType = mimeType;
    }
}