|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Buffers; |
| 5 | +using System.Net.ServerSentEvents; |
| 6 | +using System.Text; |
| 7 | +using Microsoft.AspNetCore.Http.Metadata; |
| 8 | +using System.Reflection; |
| 9 | +using Microsoft.AspNetCore.Builder; |
| 10 | +using System.Text.Json; |
| 11 | +using Microsoft.Extensions.Options; |
| 12 | +using Microsoft.AspNetCore.Http.Json; |
| 13 | +using Microsoft.Extensions.DependencyInjection; |
| 14 | + |
| 15 | +namespace Microsoft.AspNetCore.Http.HttpResults; |
| 16 | + |
| 17 | +/// <summary> |
| 18 | +/// Represents a result that writes a stream of server-sent events to the response. |
| 19 | +/// </summary> |
| 20 | +/// <typeparam name="T">The underlying type of the events emitted.</typeparam> |
| 21 | +public sealed class ServerSentEventsResult<T> : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult |
| 22 | +{ |
| 23 | + private readonly IAsyncEnumerable<SseItem<T>> _events; |
| 24 | + |
| 25 | + /// <inheritdoc/> |
| 26 | + public int? StatusCode => StatusCodes.Status200OK; |
| 27 | + |
| 28 | + internal ServerSentEventsResult(IAsyncEnumerable<T> events, string? eventType) |
| 29 | + { |
| 30 | + _events = WrapEvents(events, eventType); |
| 31 | + } |
| 32 | + |
| 33 | + internal ServerSentEventsResult(IAsyncEnumerable<SseItem<T>> events) |
| 34 | + { |
| 35 | + _events = events; |
| 36 | + } |
| 37 | + |
| 38 | + /// <inheritdoc /> |
| 39 | + public async Task ExecuteAsync(HttpContext httpContext) |
| 40 | + { |
| 41 | + ArgumentNullException.ThrowIfNull(httpContext); |
| 42 | + |
| 43 | + httpContext.Response.ContentType = "text/event-stream"; |
| 44 | + |
| 45 | + await SseFormatter.WriteAsync(_events, httpContext.Response.Body, |
| 46 | + (item, writer) => FormatSseItem(item, writer, httpContext), |
| 47 | + httpContext.RequestAborted); |
| 48 | + } |
| 49 | + |
| 50 | + private static void FormatSseItem(SseItem<T> item, IBufferWriter<byte> writer, HttpContext httpContext) |
| 51 | + { |
| 52 | + // Emit string and null values as-is |
| 53 | + if (item.Data is string stringData) |
| 54 | + { |
| 55 | + writer.Write(Encoding.UTF8.GetBytes(stringData)); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + if (item.Data is null) |
| 60 | + { |
| 61 | + writer.Write([]); |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + // For non-string types, use JSON serialization with options from DI |
| 66 | + var jsonOptions = httpContext.RequestServices.GetService<IOptions<JsonOptions>>()?.Value ?? new JsonOptions(); |
| 67 | + var runtimeType = item.Data.GetType(); |
| 68 | + var jsonTypeInfo = jsonOptions.SerializerOptions.GetTypeInfo(typeof(T)); |
| 69 | + |
| 70 | + // Use the appropriate JsonTypeInfo based on whether we need polymorphic serialization |
| 71 | + var typeInfo = jsonTypeInfo.ShouldUseWith(runtimeType) |
| 72 | + ? jsonTypeInfo |
| 73 | + : jsonOptions.SerializerOptions.GetTypeInfo(typeof(object)); |
| 74 | + |
| 75 | + var json = JsonSerializer.Serialize(item.Data, typeInfo); |
| 76 | + writer.Write(Encoding.UTF8.GetBytes(json)); |
| 77 | + } |
| 78 | + |
| 79 | + private static async IAsyncEnumerable<SseItem<T>> WrapEvents(IAsyncEnumerable<T> events, string? eventType = null) |
| 80 | + { |
| 81 | + await foreach (var item in events) |
| 82 | + { |
| 83 | + yield return new SseItem<T>(item, eventType); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + static void IEndpointMetadataProvider.PopulateMetadata(MethodInfo method, EndpointBuilder builder) |
| 88 | + { |
| 89 | + ArgumentNullException.ThrowIfNull(method); |
| 90 | + ArgumentNullException.ThrowIfNull(builder); |
| 91 | + |
| 92 | + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, typeof(SseItem<T>), contentTypes: ["text/event-stream"])); |
| 93 | + } |
| 94 | +} |
0 commit comments