如何在NancyFX中编写流输出?

Rog*_*mbe 7 nancy

我正在使用Nancy编写一个简单的Web应用程序.至少有一个请求导致未知长度的流,所以我无法提供Content-Length.我想使用Transfer-Encoding: chunked,或(在这种情况下同样可以接受Connection: close).

我已经对Nancy源代码进行了快速破解,并且我已添加Response.BufferOutput,并且代码设置HttpContext.Response.BufferOutputfalse.你可以在这里看到:

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);
                }
            };
        }
    }
Run Code Online (Sandbox Code Playgroud)

它似乎没有任何影响.5秒钟后响应立即响起.我已经测试了这个基于简单WebRequest的客户端.

如何在Nancy中使用chunked输出?我正在使用ASP.NET托管,但我对其他托管选项的答案感兴趣.

如果我写一个简单的服务器使用HttpListener,我可以设置SendChunkedtrue,并将其发送分块的输出,这我简单的客户端正确地接收数据块.

erd*_*mke 6

在我的实验中,我发现我需要以下配置.首先,web.config按照Nancy Wiki中的说明设置文件.值得注意的是,为了设置disableoutputbuffer值(这是我们想要的),您似乎还需要指定一个引导程序.在程序集中创建一个继承自Nancy.Hosting.Aspnet.DefaultNancyAspNetBootstrapper配置文件并在配置文件中指定它的类似乎可行.

<configSections>
  <section name="nancyFx" type="Nancy.Hosting.Aspnet.NancyFxSection" />
</configSections>
<nancyFx>
  <bootstrapper assembly="YourAssembly" type="YourBootstrapper"/>
  <disableoutputbuffer value="true" />
</nancyFx>
Run Code Online (Sandbox Code Playgroud)

之后,您不应该设置Transfer-Encoding标题.相反,以下路由定义似乎正确地将结果从我的IIS Express开发服务器流式传输到Chrome:

Get["/chunked"] = _ =>
{
  var response = new Response();
  response.ContentType = "text/plain";
  response.Contents = s =>
  {
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes("Hello World ");
    for (int i = 0; i < 10; ++i)
    {
      for (var j = 0; j < 86; j++)
      {
        s.Write(bytes, 0, bytes.Length);
      }
      s.WriteByte(10);
      s.Flush();
      System.Threading.Thread.Sleep(500);
    }
  };

  return response;
};
Run Code Online (Sandbox Code Playgroud)

我为每个块指定了​​比上一个示例更多的内容,因为在其他StackOverflow问题中记录了第一次渲染之前的最小大小


Rog*_*mbe 4

您必须Flush()在每个之后调用Write(),否则响应无论如何都会被缓冲。此外,Google Chrome 浏览器在全部接收到输出之前不会渲染输出。

我通过编写一个简单的客户端应用程序发现了这一点,该应用程序记录了响应流到达时所读取的内容。