首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不需要缓冲的情况下将文件从数据库异步流到webclient

问如何在不需要缓冲的情况下将文件从数据库异步流到webclient
EN

Stack Overflow用户
提问于 2013-11-26 15:04:02
回答 2查看 3.7K关注 0票数 3

我正在尝试使用.net 4.5和web将文件从sql server异步流到web客户端。

我使用SqlDataReader.GetStream()从db获取流。但是,当webapi从流中读取完时,我不知道如何连接处理/关闭db连接。

外面有样本吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-26 15:17:46

您可以编写一个包装流,该流从底层流中读取,直到耗尽为止,然后处理所有相关的资源(如SqlConnection)。

我不是WebAPI专家,所以可能有一种更优雅的方法。但是这在任何情况下都适用于对流的标准WebAPI支持。

票数 1
EN

Stack Overflow用户

发布于 2013-11-26 15:52:52

您可以在Web中执行类似的操作。在这里,我使用PushStreamContent连接到数据库并检索Sql流。然后,我将这个sql流直接复制到响应流。在Web中,当您使用PushStreamContent时,客户端将以分组传输编码的方式接收响应,因为您没有设置响应的内容长度。如果这对您来说很好,您可以使用下面的示例。否则,我将尝试看看是否还有其他更好的方法来实现这一点。

注意:这是一个基于MSDN上关于从server检索二进制数据的PushStreamContent和这文章的快速示例。

代码语言:javascript
复制
[RoutePrefix("api/values")]
public class ValuesController : ApiController
{
    private const string connectionString = @"your connection string";

    [Route("{id}")]
    public HttpResponseMessage GetImage(int id)
    {
        HttpResponseMessage resp = new HttpResponseMessage();

        resp.Content = new PushStreamContent(async (responseStream, content, context) =>
        {
            await CopyBinaryValueToResponseStream(responseStream, id);
        });

        return resp;
    }

    // Application retrieving a large BLOB from SQL Server in .NET 4.5 using the new asynchronous capability
    private static async Task CopyBinaryValueToResponseStream(Stream responseStream, int imageId)
    {
        // PushStreamContent requires the responseStream to be closed
        // for signaling it that you have finished writing the response.
        using (responseStream)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                await connection.OpenAsync();

                using (SqlCommand command = new SqlCommand("SELECT [bindata] FROM [Streams] WHERE [id]=@id", connection))
                {
                    command.Parameters.AddWithValue("id", imageId);

                    // The reader needs to be executed with the SequentialAccess behavior to enable network streaming
                    // Otherwise ReadAsync will buffer the entire BLOB into memory which can cause scalability issues or even OutOfMemoryExceptions
                    using (SqlDataReader reader = await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess))
                    {
                        if (await reader.ReadAsync())
                        {
                            if (!(await reader.IsDBNullAsync(0)))
                            {
                                using (Stream data = reader.GetStream(0))
                                {
                                    // Asynchronously copy the stream from the server to the response stream
                                    await data.CopyToAsync(responseStream);
                                }
                            }
                        }
                    }
                }
            }
        }// close response stream
    }
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20220673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档