微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 带有ExecuteReaderAsync的ASP.NET webapi HttpResponseMessage 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派生类,它包装ADO.NET返回的流,一旦流耗尽,就会处理所有内容(Stream,reader,command和connection).

解决方案意味着您不能使用块等.我真的不喜欢它,但我现在想不出更好的东西.这些要求很难组合:您需要流式传输行为并需要处理您打开的各种资源.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐