我正在使用 Nancy 编写一个简单的 Web 应用程序。至少一个请求会导致长度未知的流,因此我无法提供Content-Length
。我想用Transfer-Encoding: chunked
,或(在这种情况下同样可以接受,Connection: close
).
我对 Nancy 源代码进行了快速修改,并且添加了Response.BufferOutput
,以及要设置的代码HttpContext.Response.BufferOutput
to false
。你可以在这里看到:
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);
}
};
}
}
好像没有什么效果。 5 秒后,响应立即出现。我已经测试过这个简单的WebRequest
基于客户端。
如何让分块输出在 Nancy 中工作?我正在使用 ASP.NET 托管,但我对其他托管选项的答案感兴趣。
如果我使用编写一个简单的服务器HttpListener
,我可以设置SendChunked
to true
,并且它发送分块的输出,我的简单客户端正确地接收到分块的输出。
在我的实验过程中,我发现我需要以下配置。首先,设置您的web.config
文件中记录的南希维基 https://github.com/NancyFx/Nancy/wiki/Hosting-Nancy-with-asp.net。值得注意的是,为了设置disableoutputbuffer
value(这就是我们想要的),看来您当前还需要指定一个引导程序。在程序集中创建一个继承自的类Nancy.Hosting.Aspnet.DefaultNancyAspNetBootstrapper
并在配置文件中指定它似乎有效。
<configSections>
<section name="nancyFx" type="Nancy.Hosting.Aspnet.NancyFxSection" />
</configSections>
<nancyFx>
<bootstrapper assembly="YourAssembly" type="YourBootstrapper"/>
<disableoutputbuffer value="true" />
</nancyFx>
之后,您不应设置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;
};
由于其他文档中记录的首次渲染之前的最小大小,我为每个块指定了比前一个示例更多的内容StackOverflow 问题 https://stackoverflow.com/questions/16909227/using-transfer-encoding-chunked-how-much-data-must-be-sent-before-browsers-s
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)