加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 带有ExecuteReaderAsync的ASP.NET webapi HttpResponseMes

发布时间:2020-12-15 21:55:23 所属栏目:百科 来源:网络整理
导读:我需要通过WebApi从Sql Server传输blob数据. 我不想在Web服务器上缓冲内存中的blob数据. 我有以下代码,但它不起作用 – 没有例外. public class AttachmentController : ApiController{ public async TaskHttpResponseMessage Get(int id) { using (var conn
我需要通过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).

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读