17

We are trying to return large image files using ASP.Net WebApi and using the following code to stream the bytes to the client.

public class RetrieveAssetController : ApiController
{
    // GET api/retrieveasset/5
    public HttpResponseMessage GetAsset(int id)
    {
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
        string filePath = "SomeImageFile.jpg";

        MemoryStream memoryStream = new MemoryStream();

        FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);

        byte[] bytes = new byte[file.Length];
        file.Read(bytes, 0, (int)file.Length);

        memoryStream.Write(bytes, 0, (int)file.Length);

        file.Close();

        httpResponseMessage.Content =  new ByteArrayContent(memoryStream.ToArray());
        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        httpResponseMessage.StatusCode = HttpStatusCode.OK;

        return httpResponseMessage;
    }
}

The above code works fine but some of the files that we deal with could be 2 GB and upwards in size resulting in connection timeouts. We have used code similar to below in the past (using HttpHandlers) to chunk the response to the response stream to keep the connection alive with success.

byte[] b = new byte[this.BufferChunkSize];
int byteCountRead = 0;

while ((byteCountRead = stream.Read(b, 0, b.Length)) > 0)
{
    if (!response.IsClientConnected) break;

    response.OutputStream.Write(b, 0, byteCountRead);
    response.Flush();
}

How can we use a similar technique using the new WebAPI programming model shown earlier?

shA.t
  • 16,580
  • 5
  • 54
  • 111
raj
  • 193
  • 1
  • 1
  • 4

2 Answers2

26

Yes you can use PushStreamContent. And if you combine it with asynchronous execution (usin i.e. async lambdas), you might get even more effective results.

I have blogged about this approach earlier this month - http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/.

The example used a video file, the principle is the same - pushing down bytes of data to the client.

Filip W
  • 27,097
  • 6
  • 95
  • 82
  • @FIllip W - First of all, thank you very much for your help. I do not have the luxury of using 4.5 Framework so I cannot use the built -in Async features of 4.5 framework. Can this approach work with using 4.0 framework libraries? More specifically how would the "WriteToStream" action change? Can I just read each chunk of bytes and write to the output stream without worrying about async part? – raj Feb 05 '13 at 00:34
  • Yes everything in Web API is 4.0 compatible. You can just remove async/await and make the whole thing synchronous, or just use continuations (ContinueWith) wherever the code is awaited. – Filip W Feb 05 '13 at 00:46
  • @FIllip W - This is working nicely for me. Thank you so much for your help again. I have accepted your answer. Thanks again – raj Feb 05 '13 at 02:15
0

Stream directly from the file using StreamContent (too new?). Similar to Web API Controller convert MemoryStream into StreamContent

httpResponseMessage.Content = new StreamContent(file);
Community
  • 1
  • 1
drzaus
  • 24,171
  • 16
  • 142
  • 201
  • I'm running into serious issues (like the download not completing) with this implementation. Something is making the client think it doesn't have all of the content! – Norman H Mar 15 '18 at 19:07
  • @NormanH weird, i would think something is "interrupting" the download, either the client giving up because something is taking "too long" on the server, or could you be accidentally mangling the original filestream? I've done that before, putting a stream into something and then either disposing a reader/writer too soon (which closes the stream it's acting on, depending on a setting). Maybe you're limiting the file read, or the source file is moved/deleted in the middle of streaming? – drzaus Apr 11 '18 at 20:12