2013-08-17 2 views
4

WebApi를 통해 SQL Server에서 BLOB 데이터를 스트리밍해야합니다.ASP.NET webapi HttpResponseMessage with ExecuteReaderAsync CommandBehavior.SequentialAccess

I DONT는 웹 서버의 메모리에 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); 
     } 
    } 
} 

이 바이올린은 reposnse으로 다음과 같은 오류를 기록합니다 : 는 [피들러] ReadResponse() 실패 : 서버가이 요청에 대한 응답을 반환하지 않았습니다.

메모리에서 버퍼링하지 않고 DB의 내용을 http 출력 스트림으로 스트리밍 할 수 있습니까?

답변

1

ASP.NET MVC에서 스트림 읽기를 마치기 전에 스트림을 닫고 있습니다. return 문이 실행 된 직후에 발생하는 다양한 블록 사용을 종료하면 닫힙니다.

이 작업을 수행하는 쉬운 방법이 없습니다. 가장 좋은 방법은 사용자 정의 Stream - ADO.NET에 의해 반환 된 스트림을 래핑하고 스트림이 고갈되면 모든 것을 처리하는 것 (Stream, 판독기, 명령 및 연결)을 생성하는 것입니다.

이 솔루션은 블록 등을 사용할 수 없다는 것을 의미합니다. 나는 정말로 그것을 좋아하지 않지만 나는 더 나은 순간을 생각할 수 없다. 요구 사항을 조합하는 것은 어렵습니다. 스트리밍 동작이 필요하고 열어 놓은 다양한 리소스를 처분해야합니다.

+0

비슷한 생각 :'Dispose()'메소드를 오버라이드하는'StreamContent'에서 파생 된 맞춤 클래스를 생성하십시오. – svick