What is different with PushStreamContent between web api & web api 2?

后端 未结 5 814
难免孤独
难免孤独 2021-02-05 23:34

I\'ve created two identical web api projects, one in VS 2012 and another in VS 2013, both targeting the 4.5 .net framework. The projects are based on Filip W\'s video download t

5条回答
  •  忘了有多久
    2021-02-05 23:42

    I am not sure if this is a bug in Web API, we will investigate into it. Meanwhile you can try the following workaround:

    response.Content = new PushStreamContent(async (Stream outputStream, HttpContent content, TransportContext context) =>
    {
        try
        {
            var buffer = new byte[65536];
    
            using (var video = File.Open(filename, FileMode.Open, FileAccess.Read))
            {
                var length = (int)video.Length;
                var bytesRead = 1;
    
                while (length > 0 && bytesRead > 0)
                {
                    bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
                    await outputStream.WriteAsync(buffer, 0, bytesRead);
                    length -= bytesRead;
                }
            }
        }
        finally
        {
            outputStream.Close();
        }
    });
    

    Note: I made another change(removed the catch block) to the code to allow exceptions to propagate. This is so that your clients know that some error happened at the service otherwise they would assume everything went smooth.

提交回复
热议问题