虽然没有官方文档,但有谁知道如何使用 ASP.NET Core 实现 SSE?
While there is no official documentation, does anyone know how SSE may be implemented using ASP.NET Core?
我怀疑一种实现可能会使用自定义中间件,但也许可以在控制器操作中做到这一点?
I suspect one implementation may use custom middleware, but maybe it is possible to do that in controller action?
在页面加载时,为 http://www.somehost.ca/sse
网址创建一个 EventSource
.然后将其事件写入控制台.
On page load, create an EventSource
for the http://www.somehost.ca/sse
url. Then write its events to the console.
<body>
<script type="text/javascript">
var source = new EventSource('sse');
source.onmessage = function (event) {
console.log('onmessage: ' + event.data);
};
source.onopen = function(event) {
console.log('onopen');
};
source.onerror = function(event) {
console.log('onerror');
}
</script>
</body>
中间件处理 sse
路径.它将 Content-Type
标头设置为服务器套接字事件所需的 text/event-stream
.它写入响应流,而不关闭连接.它通过在写入之间延迟五秒钟来模仿工作.
The middleware handles the sse
path. It sets the Content-Type
header to text/event-stream
, which the server socket event requires. It writes to the response stream, without closing the connection. It mimics doing work, by delaying for five seconds between writes.
app.Use(async (context, next) =>
{
if (context.Request.Path.ToString().Equals("/sse"))
{
var response = context.Response;
response.Headers.Add("Content-Type", "text/event-stream");
for(var i = 0; true; ++i)
{
// WriteAsync requires `using Microsoft.AspNetCore.Http`
await response
.WriteAsync($"data: Middleware {i} at {DateTime.Now}
");
await response.Body.FlushAsync();
await Task.Delay(5 * 1000);
}
}
await next.Invoke();
});
控制器的作用与中间件完全相同.
The controller does the exact same thing as the middleware does.
[Route("/api/sse")]
public class ServerSentEventController : Controller
{
[HttpGet]
public async Task Get()
{
var response = Response;
response.Headers.Add("Content-Type", "text/event-stream");
for(var i = 0; true; ++i)
{
await response
.WriteAsync($"data: Controller {i} at {DateTime.Now}
");
response.Body.Flush();
await Task.Delay(5 * 1000);
}
}
}
这是 Firefox 控制台窗口中的结果.每五秒钟就有一条新消息到达.
This is the result in the Firefox console window. Every five seconds a new messages arrives.
onopen
onmessage: Message 0 at 4/15/2016 3:39:04 PM
onmessage: Message 1 at 4/15/2016 3:39:09 PM
onmessage: Message 2 at 4/15/2016 3:39:14 PM
onmessage: Message 3 at 4/15/2016 3:39:19 PM
onmessage: Message 4 at 4/15/2016 3:39:24 PM
参考文献:
这篇关于ASPNET Core 服务器发送事件/响应刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!