Skip to content

Instantly share code, notes, and snippets.

@HamidMolareza
Last active June 24, 2024 21:15
Show Gist options
  • Save HamidMolareza/f17109f6b49a308c5836b74f61072e52 to your computer and use it in GitHub Desktop.
Save HamidMolareza/f17109f6b49a308c5836b74f61072e52 to your computer and use it in GitHub Desktop.
Server-Sent Events (sse) sample as minimal API in ASP
app.MapGet("/sse/connect", async (HttpContext context, CancellationToken ct) => {
context.Response.Headers.Append("Content-Type", "text/event-stream");
context.Response.Headers.Append("Cache-Control", "no-cache");
context.Response.Headers.Append("Connection", "keep-alive");
var result = new SSEResult();
for (var i = 0; i < 10; i++) {
if (ct.IsCancellationRequested) return;
result.DateTime = DateTime.Now;
await context.Response.WriteAsync("data:", cancellationToken: ct);
await JsonSerializer.SerializeAsync(context.Response.Body, result, cancellationToken: ct);
await context.Response.WriteAsync("\n\n", cancellationToken: ct);
await context.Response.Body.FlushAsync(ct); //ensures that the data is sent immediately.
await Task.Delay(1000, ct);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment