2016-07-03 3 views
2

OWIN 자체 호스트 응용 프로그램에서 MVC 작업을 사용하여 클라이언트에 파일을 대량으로 제공합니다. 데이터가 메모리 내에서 생성되고 캐시되며 MVC 작업은 StreamContentMemoryStream으로 반환하여 캐시 된 byte[]을 가리 킵니다.출력 스트림에 직접 OWIN 자체 호스트 MVC 쓰기를 만드는 방법

데이터가 내 캐시에서 직접 읽히고 OutputStream에 복사 될 것으로 예상됩니다. 대신 데이터는 내 MemoryStream에서 인프라 스트럭처에 의해 생성 된 다른 데이터로 복사됩니다.

return new HttpResponseMessage(HttpStatusCode.OK) 
{ 
    Content = new StreamContent(new MemoryStream(content), content.Length) 
    { 
     Headers = 
     { 
      ContentDisposition = new ContentDispositionHeaderValue("attachment") 
      { 
       FileNameStar = fileName, 
       Size = content.Length, 
      }, 
      ContentType = MediaTypeHeaderValue.Parse(mediaType), 
      ContentLength = content.Length, 
     } 
    } 
}; 

어떻게 내가 돌려 확인 할 수 있습니다 내가 더 많은 메모리를 차지하는 복사 직접하지 않고 MemoryStream 캐시 : 병렬로 많은 요청을 할 때 나는 프로세스 메모리가 증가 볼 수 있습니까?

답변

1

이것을 극복하려면 OWIN 환경에서 Request.GetOwinEnvironment()으로 가져 와서 OutputStream에 직접 쓸 수 있습니다. 작성된 응답 내용을 얻으려면 PushStreamContent을 사용하고 응답이 생성 될 때 호출되는 async 콜백을 사용하여 OutputStream에 쓸 수 있습니다.

var outputStream = ((HttpListenerContext)Request.GetOwinEnvironment()["System.Net.HttpListenerContext"]).Response.OutputStream; 
    return new HttpResponseMessage(HttpStatusCode.OK) 
    { 
     Content = new PushStreamContent(
      async (stream, httpContent, arg3) => 
      { 
       await outputStream.WriteAsync(content, 0, content.Length); 
       stream.Close(); 
      }) 
     { 
      Headers = 
      { 
       ContentDisposition = new ContentDispositionHeaderValue("attachment") 
       { 
        FileNameStar = fileName, 
        Size = content.Length, 
       }, 
       ContentType = MediaTypeHeaderValue.Parse(mediaType), 
       ContentLength = content.Length, 
      } 
     } 
    }; 
관련 문제