使用WebAPI流式传输MJPEG总是缓冲



我正在使用httpself hostconfiguration创建WebAPI(服务(。我的目标是让一个路由从安全供稿流传输MJPEG视频,并提供其他可用于配置和Web界面的路由。

我遇到的问题是,我遇到的每个示例都期望已知数量的图像,以便为主要响应设置内容长度。我没有这个,冲洗流也无能为力。

这是响应的当前代码。如果我使用原始插座而不是通过apicontroller使用相同的代码,我可以很好地将其流式传输,但是从头开始创建一个我所需要的其他所有内容的Web服务器似乎并没有很多乐趣。

>
[HttpGet]
public HttpResponseMessage Stream(int channel)
{
    var response = Request.CreateResponse();
    response.Content = new PushStreamContent((outputStream, content, context) =>
    {
        StreamWriter writer = new StreamWriter(outputStream);
        while (true)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                ReadMemoryMappedFile(channel);
                ms.SetLength(0);
                this.Image.Bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] buffer = ms.GetBuffer();

                writer.WriteLine("--boundary");
                writer.WriteLine("Content-Type: image/jpeg");
                writer.WriteLine(string.Format("Content-length: {0}", buffer.Length));
                writer.WriteLine();
                writer.Write(buffer);
                writer.Flush();
            }
        }
    });
    response.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/x-mixed-replace; boundary=--boundary");
    return response;
}

我希望我的晚回答会有所帮助,因为我最近遇到了同一问题,我花了一些时间来弄清楚它...

我的解决方案是指定boudary int contentType,而没有" - "(但是您需要在流中写作时保留它们(。

尝试配置这样的标题:

response.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/x-mixed-replace; boundary=boundary");

并像这样在流中写边界:

writer.WriteLine("--boundary");

这样它对我有用。

我找不到明确说明这一点的任何地方在释放缓冲区之前。

我用owin.self -host交换了httpself hostconfiguration,它可以按预期工作。

最新更新