Add Shared Server-Sent Events Helpers

- Add XSseExtensions: PrepareSseResponse, WriteSseEventAsync, WriteSseRawAsync,
  WriteSseDoneAsync, WriteSseErrorAsync, IsClientCancellation;
- Spec-compliant "data:" framing, multi-line split, "event: done" / "event: error";
- Add Microsoft.AspNetCore.Http.Features 2.3.13 reference.
This commit is contained in:
2026-10-29 19:58:21 +03:30
parent d412141193
commit f3372333fd
2 changed files with 148 additions and 0 deletions
+147
View File
@@ -0,0 +1,147 @@
using System;
using System.Text;
using System.Threading;
using xCommons.Extensions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
namespace xHttpService.Extensions
{
/// <summary>
/// Server-Sent Events (SSE) Helpers ...
/// Format (per Spec): [event: name\n] data: line\n ... \n
/// </summary>
public static class XSseExtensions
{
//
// Event Names ...
public const string SseDoneEvent = "done";
public const string SseErrorEvent = "error";
public const string SseContentType = "text/event-stream; charset=utf-8";
/// <summary>
/// Configure Response for SSE (Headers + Disable Buffering) ...
/// Must be Called before any Write ...
/// </summary>
/// <param name="source"></param>
public static void PrepareSseResponse(
this HttpResponse source
)
{
//
if (source.IsNull() || source.HasStarted)
{
return;
}
//
source.StatusCode = StatusCodes.Status200OK;
source.ContentType = SseContentType;
source.Headers["Cache-Control"] = "no-cache, no-store";
source.Headers["X-Accel-Buffering"] = "no";
//
// Disable Response Buffering ...
source.HttpContext.Features
.Get<IHttpBufferingFeature>()?
.DisableResponseBuffering();
}
/// <summary>
/// Write an Object as JSON (camelCase) SSE Event ...
/// </summary>
public static Task WriteSseEventAsync<T>(
this HttpResponse source,
T data,
string eventName = null,
CancellationToken cancellationToken = default
)
{
//
var payload = data.IsNull()
? "null"
: data.ToJSON(camelCase: true);
//
return source.WriteSseRawAsync(payload, eventName, cancellationToken);
}
/// <summary>
/// Write Raw Text as SSE Event (Multi Line Text is Split into Multiple data: Lines) ...
/// </summary>
public static async Task WriteSseRawAsync(
this HttpResponse source,
string payload,
string eventName = null,
CancellationToken cancellationToken = default
)
{
//
var builder = new StringBuilder();
if (!eventName.IsNullOrEmpty())
{
builder.Append("event: ").Append(eventName).Append('\n');
}
//
var normalized = (payload ?? string.Empty)
.Replace("\r\n", "\n")
.Replace('\r', '\n');
foreach (var line in normalized.Split('\n'))
{
builder.Append("data: ").Append(line).Append('\n');
}
builder.Append('\n');
//
await source.WriteAsync(builder.ToString(), Encoding.UTF8, cancellationToken);
await source.Body.FlushAsync(cancellationToken);
}
/// <summary>
/// Write Terminating "done" Event ...
/// </summary>
public static Task WriteSseDoneAsync(
this HttpResponse source,
CancellationToken cancellationToken = default
)
{
return source.WriteSseRawAsync("[DONE]", SseDoneEvent, cancellationToken);
}
/// <summary>
/// Write "error" Event (Never Throws; Used when Stream has Already Started) ...
/// </summary>
public static async Task WriteSseErrorAsync(
this HttpResponse source,
string message
)
{
//
try
{
await source.WriteSseEventAsync(
data: new { error = message ?? "Stream Failed" },
eventName: SseErrorEvent,
cancellationToken: CancellationToken.None
);
}
catch
{
// Client Gone ...
}
}
/// <summary>
/// Is Exception Caused by Client Disconnect / Cancellation ...
/// </summary>
public static bool IsClientCancellation(
this Exception source,
CancellationToken cancellationToken
)
{
return source is OperationCanceledException && cancellationToken.IsCancellationRequested;
}
}
}