我需要通过 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 将以下错误作为响应写入:[Fiddler] ReadResponse() failed: 服务器没有针对此请求返回响应。
如何将内容从 DB 流式传输到 http 输出流,而不将其缓冲在内存中?