我正在尝试使用.net 4.5和web将文件从sql server异步流到web客户端。
我使用SqlDataReader.GetStream()从db获取流。但是,当webapi从流中读取完时,我不知道如何连接处理/关闭db连接。
外面有样本吗?
发布于 2013-11-26 15:17:46
您可以编写一个包装流,该流从底层流中读取,直到耗尽为止,然后处理所有相关的资源(如SqlConnection)。
我不是WebAPI专家,所以可能有一种更优雅的方法。但是这在任何情况下都适用于对流的标准WebAPI支持。
发布于 2013-11-26 15:52:52
您可以在Web中执行类似的操作。在这里,我使用PushStreamContent连接到数据库并检索Sql流。然后,我将这个sql流直接复制到响应流。在Web中,当您使用PushStreamContent时,客户端将以分组传输编码的方式接收响应,因为您没有设置响应的内容长度。如果这对您来说很好,您可以使用下面的示例。否则,我将尝试看看是否还有其他更好的方法来实现这一点。
注意:这是一个基于MSDN上关于从server检索二进制数据的PushStreamContent和这文章的快速示例。
[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
}
}https://stackoverflow.com/questions/20220673
复制相似问题