ASPNET Core Server dispatched events / response flow

While there is no official documentation, does anyone know how SSE can be implemented using ASP.NET Core?

I suspect that one implementation may use special middleware, but is it possible to do this in a controller action?

+7
c # asp.net-core asp.net-core-mvc
source share
1 answer

Wwwroot / index.html

When loading the page, create an EventSource for the URL http://www.somehost.ca/sse . Then write his 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> 

Middleware

Medium- sse software processes the sse path. It sets the Content-Type header to text/event-stream , which is required for the server socket event. It records the response flow without closing the connection. He imitates work, lingering for five seconds between spellings.

 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"); response.Body.Flush(); await Task.Delay(5 * 1000); } } await next.Invoke(); }); 

controller

The controller does the same thing as middleware.

 [Route("/api/sse")] public class ServerSentEventController { private readonly IHttpContextAccessor _httpContextAccessor; public ServerSentEventController( IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } [HttpGet] public async Task Get() { var response = _httpContextAccessor.HttpContext.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); } } } 

Console output in Firefox

This is the result in the Firefox console window. Every five seconds, new messages appear.

 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 

References:

+24
source share

All Articles