如何使用 Nancy 编写 MJPEG 服务器?

How can I write an MJPEG server using Nancy?

我有以下内容:

public sealed class ServerModule : NancyModule
{
    public ServerModule()
    {
        Get["/video"] = o =>
        {
            byte[] img = GetImage("whatever.jpeg");

            return new MjpegResponse(firstImg);
        };
    }

    private sealed class MjpegResponse : Response
    {
        public MjpegResponse(byte[] data)
        {
            this.Headers.Clear();
            this.Headers.Add("Server", "IP Webcam Server 1.5");
            this.Headers.Add("Connection", "close");
            this.Headers.Add("Cache-Control", "no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0");
            this.Headers.Add("Pragma", "no-cache");
            this.Headers.Add("Expires", "-1");
            this.Headers.Add("Access-Control-Allow-Origin", "*");

            this.ContentType = "multipart/x-mixed-replace;boundary=Ba4oTvQMY8ew04N8dcnM";

            var footer = Encoding.ASCII.GetBytes("\r\n");
            this.Contents = stream =>
            {
                using(var writer = new BinaryWriter(stream))
                {
                  writer.Write(data);
                  writer.Write(footer);
                }
            };
        }
    }
}

headers 与我从具有 built-in MJPEG 服务器的 IPCamera 获得的 headers 匹配,即使 Fiddler 显示正确的 headers:

HTTP/1.1 200 OK
Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: multipart/x-mixed-replace;boundary=Ba4oTvQMY8ew04N8dcnM
Expires: -1
Server: IP Webcam Server 1.5 Microsoft-HTTPAPI/2.0
Access-Control-Allow-Origin: *
Date: Tue, 24 Nov 2015 21:23:29 GMT
Connection: close

在启用 MJPEG 的浏览器 (Firefox) 中尝试时,它无法流式传输或显示任何内容。我注意到的另一件事是 Transfer-Encoding: chunked 不应该出现。

有什么想法吗?

我认为这里的问题很容易解决。写入流后,它指向它的末尾。在返回响应之前,您需要将该指针倒回到流的开头:

   stream.Seek(0, SeekOrigin.Begin);