![](/img/trans.png)
[英]SQLDataLReader and CommandBehavior.SequentialAccess
[英]ASP.NET webapi HttpResponseMessage with ExecuteReaderAsync CommandBehavior.SequentialAccess
我需要通过WebApi从Sql Server传输blob数据。
我不想在Web服务器上缓冲内存中的blob数据。
我有以下代码,但它不起作用 - 没有例外。
public class AttachmentController : ApiController
{
public async Task<HttpResponseMessage> Get(int id)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
await connection.OpenAsync();
using (var command = new SqlCommand("SELECT Content FROM [Attachments] WHERE ID = @ID", connection))
{
command.Parameters.AddWithValue("ID", id);
using (SqlDataReader reader = await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess))
{
if (await reader.ReadAsync())
{
using (Stream data = reader.GetStream(0))
{
var response = new HttpResponseMessage{Content = new StreamContent(data)};
//I get this from the DB else where
//response.Content.Headers.ContentType = new MediaTypeHeaderValue(attachment.ContentType);
//I get this from the DB else where
//response.Content.Headers.ContentLength = attachment.ContentLength;
return response;
}
}
}
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
}
Fiddle将以下错误写为reposnse:[Fiddler] ReadResponse()失败:服务器未返回此请求的响应。
如何将内容从数据库流式传输到http输出流,而不在内存中缓冲它?
在ASP.NET MVC完成读取之前,您正在关闭流。 一旦你离开各种使用块,它将在return
语句执行后立即关闭。
我知道没有简单的方法来实现这一目标。 最好的想法是编写一个自定义的Stream
-derived类,它包装ADO.NET返回的流,一旦流耗尽,就会处理所有内容( Stream
,reader,command和connection)。
此解决方案意味着您不能使用块等。 我真的不喜欢它,但我现在想不出更好的东西。 这些要求很难组合:您需要流式传输行为并需要处理您打开的各种资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.