ASPNET核心服务器发送事件/响应刷新

时间:2016-03-25 20:30:46

标签: c# asp.net-core asp.net-core-mvc asp.net-core-1.0

虽然没有官方文档,但有谁知道如何使用ASP.NET Core实现SSE?

我怀疑一个实现可能会使用自定义中间件,但也许可以在控制器操作中执行此操作?

2 个答案:

答案 0 :(得分:35)

<强>的wwwroot / index.html中

在页面加载时,为EventSource网址创建http://www.somehost.ca/sse。然后将其事件写入控制台。

<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,服务器套接字事件需要该标头。它写入响应流,而不关闭连接。它通过在写入之间延迟五秒来模仿工作。

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}\r\r");

            await response.Body.FlushAsync();
            await Task.Delay(5 * 1000);
        }
    }

    await next.Invoke();
});

<强>控制器

控制器与中间件完全相同。

[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}\r\r");

            response.Body.Flush();
            await Task.Delay(5 * 1000);
        }
    }
}

Firefox中的控制台输出

这是Firefox控制台窗口中的结果。每五秒钟就有一条新消息到来。

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

参考文献:

答案 1 :(得分:3)

服务器发送的事件可以完全通过控制器操作来实现。

这是基于Shaun Luttin的回答的,但它更像是一个真实的示例,因为它将无限期地保持打开连接,并根据创建的消息将消息发送到EventSource

using Example.Models;
using Example.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Example.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SseMessagesController : ControllerBase
    {
        private readonly IMessageRepository messageRepository;
        private readonly JsonSerializerSettings jsonSettings;

        public SseMessagesController(IMessageRepository messageRepository)
        {
            this.messageRepository = messageRepository;
            this.jsonSettings = new JsonSerializerSettings();
            jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }

        [HttpGet]
        public async Task GetMessages(CancellationToken cancellationToken)
        {
            Response.StatusCode = 200;
            Response.Headers.Add("Content-Type", "text/event-stream");

            EventHandler<MessageCreatedArgs> onMessageCreated = async (sender, eventArgs) =>
            {
                try
                {
                    var message = eventArgs.Message;
                    var messageJson = JsonConvert.SerializeObject(message, jsonSettings);
                    await Response.WriteAsync($"data:{messageJson}\n\n");
                    await Response.Body.FlushAsync();
                }
                catch (Exception)
                {
                    // TODO: log error
                }
            };
            messageRepository.MessageCreated += onMessageCreated;

            while (!cancellationToken.IsCancellationRequested) {
                await Task.Delay(1000);
            }

            messageRepository.MessageCreated -= onMessageCreated;
        }
    }
}

每当EventSource连接到/api/ssemessages时,我们都会向消息存储库中的MessageCreated事件添加事件委托。然后,我们每1秒检查一次EventSource是否已关闭,这将导致请求被取消。取消请求后,我们将删除事件委托。

事件委托从事件参数获取Message对象,将其序列化为JSON(使用驼峰式大小写以与ASP.NET Core返回对象结果时的默认行为一致),将JSON写入正文,并刷新主体的流,以将数据推送到EventSource

有关创建事件委托的更多信息,请参见this articlethis update for .NET Core

此外,如果将其托管在Nginx后面,则需要阅读this SO answerthis ServerFault answer