我需要通过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派生类,它包装ADO.NET返回的流,一旦流耗尽,就会处理所有内容(Stream,reader,command和connection).
此解决方案意味着您不能使用块等.我真的不喜欢它,但我现在想不出更好的东西.这些要求很难组合:您需要流式传输行为并需要处理您打开的各种资源.
查看更多关于c# – 带有ExecuteReaderAsync的ASP.NET webapi HttpRespo的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did69404