How do I write streamed output in NancyFX?

Viewed 6974

I'm writing a simple web application using Nancy. At least one request results in a stream of unknown length, so I can't provide Content-Length. I'd like to use Transfer-Encoding: chunked, or (equally acceptable in this case, Connection: close).

I've had a quick hack on the Nancy source code, and I've add Response.BufferOutput, and code to set HttpContext.Response.BufferOutput to false. You can see that here:

public class HomeModule : NancyModule
{
    public HomeModule()
    {
        Get["/slow"] = _ => new SlowStreamResponse();
    }

    private class SlowStreamResponse : Response
    {
        public SlowStreamResponse()
        {
            ContentType = "text/plain";
            BufferOutput = false;
            Contents = s => {
                byte[] bytes = Encoding.UTF8.GetBytes("Hello World\n");
                for (int i = 0; i < 10; ++i)
                {
                    s.Write(bytes, 0, bytes.Length);
                    Thread.Sleep(500);
                }
            };
        }
    }

It doesn't seem to have any effect. The response turns up all at once, after 5 seconds. I've tested this a simple WebRequest-based client.

How do I get chunked output to work in Nancy? I'm using the ASP.NET hosting, but I'd be interested in answers for the other hosting options.

If I write a simple server using HttpListener, I can set SendChunked to true, and it sends chunked output, which my simple client correctly receives in chunks.

3 Answers
Related