这个问题是由于Flush()
无法正常工作ASP.NET MVC启用压缩时似乎会自动缓冲的项目,可以通过以下方式对动态页面禁用它:
<system.webServer>
<urlCompression doStaticCompression="true" doDynamicCompression="false" />
</system.webServer>
顺便说一句,当启用压缩时,甚至用于缓冲输出的显式 API 似乎也没有任何效果:
Response.BufferOutput = false;
不使用 ASP.NET MVC 的普通 ASP.NET 项目,例如服务堆栈+剃刀 http://razor.servicestack.net/没有这个问题。
替代的纯代码解决方案
添加了新的 API https://github.com/ServiceStack/ServiceStack/commit/786ff8d055870a559f0c8a094c67ef02a5bab778 in v4.0.32+ that's 现已在 MyGet 上提供 https://github.com/ServiceStack/ServiceStack/wiki/MyGet为 ServiceStack 的服务器事件功能提供更多自定义挂钩,OnInit
可用于修改服务器事件流的 HTTP 标头,同时OnPublish()
每条消息发布后都会触发回调:
Plugins.Add(new ServerEventsFeature {
/*
OnInit = req => { //fired when sending headers in server event stream
var res = (HttpResponseBase)req.Response.OriginalResponse; //Get MVC Response
res.BufferOutput = false; // Should make Flush() work, but doesn't
},
*/
OnPublish = (res, msg) => { //fired after ever message is published
res.Write("\n\n\n\n\n\n\n\n\n\n");
res.Flush();
}
});
上面的解决方案涉及编写一些尾随\n
线路到强制冲洗在 MVC 中。这是一个有效的替代解决方案,因为服务器发送事件中会忽略尾随的新行。