Last active
June 24, 2024 21:15
-
-
Save HamidMolareza/f17109f6b49a308c5836b74f61072e52 to your computer and use it in GitHub Desktop.
Server-Sent Events (sse) sample as minimal API in ASP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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