ASP.NET Core 10
.NET 9 中我们支持了 SseItem 我们可以借助它来解析 ServerSentEvent 的 response,在 .NET 10 进一步增加了 SseItem 并在 ASP.NET Core 中原生支持了返回 ServerSentEvent 结果,在 server 端返回 sse 结果变得更加容易

Server-Sent Events (SSE) 是一种由服务器主动向浏览器单向推送数据的技术。与传统的轮询或 WebSocket 不同,SSE 使用 HTTP 协议 建立一个持久连接,然后由服务器不断通过这个连接发送事件数据给客户端。
| 特性 | SSE | WebSocket | HTTP 轮询 |
|---|---|---|---|
| 通信方向 | 服务器 → 客户端(单向) | 双向 | 客户端主动请求 |
| 协议 | 基于 HTTP | 独立的 WebSocket 协议 | HTTP |
| 实现复杂度 | 简单 | 相对复杂 | 简单但效率低 |
| 兼容性 | 大多数现代浏览器支持 | 大多数现代浏览器支持 | 所有浏览器 |
| 重连机制 | 内置 | 需手动实现 | 无需(每次新连接) |
如果需求只是 服务端向浏览器实时推送数据(例如消息通知、实时数据流),SSE 通常比 WebSocket 更轻量且实现简单。
References
-
https://developer.mozilla.org/en-US/docs/Web/API/EventSource
-
https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
-
https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
-
https://source.dot.net/#System.Net.ServerSentEvents/System/Net/ServerSentEvents/SseItem.cs,cf62e7e50c935179
-
https://github.com/dotnet/runtime/issues/98105
-
https://github.com/dotnet/runtime/pull/102238
-
https://github.com/dotnet/runtime/issues/109294
-
https://github.com/dotnet/aspnetcore/issues/56172
-
https://github.com/dotnet/aspnetcore/pull/60616
-
https://github.com/dotnet/aspnetcore/issues/64183
-
https://www.encora.com/insights/real-time-communication-simplified-a-deep-dive-into-server-sent-events-sse
-
https://github.com/WeihanLi/SamplesInPractice/blob/d99879160837c8d36c3f68eadb6c1e51c507f89c/net10sample/Net10Samples/AspNetCoreSample.cs#L29
