| | | 1 | | |
| | | 2 | | |
| | | 3 | | using System.Collections; |
| | | 4 | | using System.Globalization; |
| | | 5 | | using System.Security.Claims; |
| | | 6 | | using Kestrun.Hosting.Options; |
| | | 7 | | using Kestrun.SignalR; |
| | | 8 | | using Kestrun.Utilities; |
| | | 9 | | using Microsoft.AspNetCore.Authentication; |
| | | 10 | | using Microsoft.AspNetCore.Http.Features; |
| | | 11 | | |
| | | 12 | | namespace Kestrun.Models; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Represents the context for a Kestrun request, including the request, response, HTTP context, and host. |
| | | 16 | | /// </summary> |
| | | 17 | | public sealed record KestrunContext |
| | | 18 | | { |
| | 1 | 19 | | private static readonly IReadOnlyDictionary<string, string> EmptyStrings = |
| | 1 | 20 | | new Dictionary<string, string>(StringComparer.Ordinal); |
| | | 21 | | /// <summary> |
| | | 22 | | /// Initializes a new instance of the <see cref="KestrunContext"/> class. |
| | | 23 | | /// This constructor is used when creating a new KestrunContext from an existing HTTP context. |
| | | 24 | | /// It initializes the KestrunRequest and KestrunResponse based on the provided HttpContext |
| | | 25 | | /// </summary> |
| | | 26 | | /// <param name="host">The Kestrun host.</param> |
| | | 27 | | /// <param name="httpContext">The associated HTTP context.</param> |
| | 146 | 28 | | public KestrunContext(Hosting.KestrunHost host, HttpContext httpContext) |
| | | 29 | | { |
| | 146 | 30 | | ArgumentNullException.ThrowIfNull(host); |
| | 146 | 31 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | | 32 | | |
| | 146 | 33 | | Host = host; |
| | 146 | 34 | | HttpContext = httpContext; |
| | | 35 | | // Initialize TraceIdentifier, Request, and Response |
| | 146 | 36 | | TraceIdentifier = HttpContext.TraceIdentifier; |
| | 146 | 37 | | Request = KestrunRequest.NewRequestSync(HttpContext); |
| | | 38 | | |
| | | 39 | | // Ensure contexts created via this constructor always have a valid response. |
| | 146 | 40 | | Response = new KestrunResponse(this, 8192); |
| | | 41 | | // Routing metadata may not always be available (e.g., middleware/tests/exception handlers). |
| | | 42 | | // Fall back to the request path if no RouteEndpoint is present. |
| | 146 | 43 | | var routeEndpoint = Request.HttpContext.GetEndpoint() as RouteEndpoint; |
| | | 44 | | |
| | 146 | 45 | | var pattern = routeEndpoint?.RoutePattern.RawText; |
| | | 46 | | |
| | 146 | 47 | | if (string.IsNullOrWhiteSpace(pattern)) |
| | | 48 | | { |
| | 28 | 49 | | pattern = "/"; |
| | | 50 | | } |
| | | 51 | | |
| | 146 | 52 | | var verb = string.IsNullOrWhiteSpace(Request.Method) |
| | 146 | 53 | | ? HttpVerb.Get |
| | 146 | 54 | | : HttpVerbExtensions.FromMethodString(Request.Method); |
| | | 55 | | |
| | 146 | 56 | | if (!Host.RegisteredRoutes.TryGetValue((pattern, verb), out var options)) |
| | | 57 | | { |
| | | 58 | | // default options |
| | 134 | 59 | | options = new MapRouteOptions() |
| | 134 | 60 | | { |
| | 134 | 61 | | Pattern = pattern, |
| | 134 | 62 | | HttpVerbs = [verb] |
| | 134 | 63 | | }; |
| | | 64 | | } |
| | | 65 | | |
| | 146 | 66 | | MapRouteOptions = options; |
| | 146 | 67 | | } |
| | | 68 | | |
| | | 69 | | /// <summary> |
| | | 70 | | /// The Kestrun host associated with this context. |
| | | 71 | | /// </summary> |
| | 343 | 72 | | public Hosting.KestrunHost Host { get; init; } |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// The logger associated with the Kestrun host. |
| | | 76 | | /// </summary> |
| | 14 | 77 | | public Serilog.ILogger Logger => Host.Logger; |
| | | 78 | | /// <summary> |
| | | 79 | | /// The Kestrun request associated with this context. |
| | | 80 | | /// </summary> |
| | 941 | 81 | | public KestrunRequest Request { get; init; } |
| | | 82 | | /// <summary> |
| | | 83 | | /// The Kestrun response associated with this context. |
| | | 84 | | /// </summary> |
| | 266 | 85 | | public KestrunResponse Response { get; private set; } |
| | | 86 | | /// <summary> |
| | | 87 | | /// The ASP.NET Core HTTP context associated with this Kestrun context. |
| | | 88 | | /// </summary> |
| | 646 | 89 | | public HttpContext HttpContext { get; init; } |
| | | 90 | | |
| | | 91 | | /// <summary> |
| | | 92 | | /// Gets the route options associated with this response. |
| | | 93 | | /// </summary> |
| | 154 | 94 | | public MapRouteOptions MapRouteOptions { get; init; } |
| | | 95 | | /// <summary> |
| | | 96 | | /// Returns the ASP.NET Core session if the Session middleware is active; otherwise null. |
| | | 97 | | /// </summary> |
| | 14 | 98 | | public ISession? Session => HttpContext.Features.Get<ISessionFeature>()?.Session; |
| | | 99 | | |
| | | 100 | | /// <summary> |
| | | 101 | | /// True if Session middleware is active for this request. |
| | | 102 | | /// </summary> |
| | 4 | 103 | | public bool HasSession => Session is not null; |
| | | 104 | | |
| | | 105 | | /// <summary> |
| | | 106 | | /// Try pattern to get session without exceptions. |
| | | 107 | | /// </summary> |
| | | 108 | | public bool TryGetSession(out ISession? session) |
| | | 109 | | { |
| | 2 | 110 | | session = Session; |
| | 2 | 111 | | return session is not null; |
| | | 112 | | } |
| | | 113 | | |
| | | 114 | | /// <summary> |
| | | 115 | | /// Gets the cancellation token that is triggered when the HTTP request is aborted. |
| | | 116 | | /// </summary> |
| | 1 | 117 | | public CancellationToken Ct => HttpContext.RequestAborted; |
| | | 118 | | /// <summary> |
| | | 119 | | /// Gets the collection of key/value pairs associated with the current HTTP context. |
| | | 120 | | /// </summary> |
| | 3 | 121 | | public IDictionary<object, object?> Items => HttpContext.Items; |
| | | 122 | | |
| | | 123 | | /// <summary> |
| | | 124 | | /// Gets the resolved request culture when localization middleware is enabled. |
| | | 125 | | /// </summary> |
| | | 126 | | public bool HasRequestCulture => |
| | 8 | 127 | | HttpContext.Items.TryGetValue("KrCulture", out var value) && value is string culture && !string.IsNullOrWhiteSpa |
| | | 128 | | |
| | | 129 | | /// <summary> |
| | | 130 | | /// Gets the resolved request culture when localization middleware is enabled. |
| | | 131 | | /// </summary> |
| | | 132 | | public string Culture => |
| | 0 | 133 | | HttpContext.Items.TryGetValue("KrCulture", out var value) && value is string culture && !string.IsNullOrWhiteSpa |
| | 0 | 134 | | ? culture |
| | 0 | 135 | | : CultureInfo.CurrentCulture.Name; |
| | | 136 | | |
| | | 137 | | /// <summary> |
| | | 138 | | /// Gets the localized string table for the resolved culture when localization middleware is enabled. |
| | | 139 | | /// </summary> |
| | | 140 | | public IReadOnlyDictionary<string, string> LocalizedStrings => |
| | 4 | 141 | | HttpContext.Items.TryGetValue("KrStrings", out var value) && value is IReadOnlyDictionary<string, string> string |
| | 4 | 142 | | ? strings |
| | 4 | 143 | | : EmptyStrings; |
| | | 144 | | |
| | | 145 | | /// <summary> |
| | | 146 | | /// Gets the localized string table for the resolved culture when localization middleware is enabled. |
| | | 147 | | /// </summary> |
| | 0 | 148 | | public IReadOnlyDictionary<string, string> Strings => LocalizedStrings; |
| | | 149 | | |
| | | 150 | | /// <summary> |
| | | 151 | | /// Gets the user associated with the current HTTP context. |
| | | 152 | | /// </summary> |
| | 2 | 153 | | public ClaimsPrincipal User => HttpContext.User; |
| | | 154 | | |
| | | 155 | | /// <summary> |
| | | 156 | | /// Gets the connection information for the current HTTP context. |
| | | 157 | | /// </summary> |
| | 0 | 158 | | public ConnectionInfo Connection => HttpContext.Connection; |
| | | 159 | | |
| | | 160 | | /// <summary> |
| | | 161 | | /// Gets the trace identifier for the current HTTP context. |
| | | 162 | | /// </summary> |
| | 153 | 163 | | public string TraceIdentifier { get; init; } |
| | | 164 | | |
| | | 165 | | /// <summary> |
| | | 166 | | /// A dictionary to hold parameters passed by user for use within the KestrunContext. |
| | | 167 | | /// </summary> |
| | 184 | 168 | | public ResolvedRequestParameters Parameters { get; internal set; } = new ResolvedRequestParameters(); |
| | | 169 | | |
| | | 170 | | /// <summary> |
| | | 171 | | /// Returns a string representation of the KestrunContext, including path, user, and session status. |
| | | 172 | | /// </summary> |
| | | 173 | | public override string ToString() |
| | 2 | 174 | | => $"KestrunContext{{ Host={Host}, Path={HttpContext.Request.Path}, User={User?.Identity?.Name ?? "<anon>"}, Has |
| | | 175 | | |
| | | 176 | | /// <summary> |
| | | 177 | | /// Asynchronously broadcasts a log message to all connected SignalR clients using the IRealtimeBroadcaster service. |
| | | 178 | | /// </summary> |
| | | 179 | | /// <param name="level">The log level (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 180 | | /// <param name="message">The log message to broadcast.</param> |
| | | 181 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 182 | | /// <returns>True if the log was broadcast successfully; otherwise, false.</returns> |
| | | 183 | | public async Task<bool> BroadcastLogAsync(string level, string message, CancellationToken cancellationToken = defaul |
| | | 184 | | { |
| | 4 | 185 | | var svcProvider = HttpContext.RequestServices; |
| | | 186 | | |
| | 4 | 187 | | if (svcProvider == null) |
| | | 188 | | { |
| | 1 | 189 | | Logger.Warning("No service provider available to resolve IRealtimeBroadcaster."); |
| | 1 | 190 | | return false; |
| | | 191 | | } |
| | 3 | 192 | | if (svcProvider.GetService(typeof(IRealtimeBroadcaster)) is not IRealtimeBroadcaster broadcaster) |
| | | 193 | | { |
| | 1 | 194 | | Logger.Warning("IRealtimeBroadcaster service is not registered. Make sure SignalR is configured with Kestrun |
| | 1 | 195 | | return false; |
| | | 196 | | } |
| | | 197 | | try |
| | | 198 | | { |
| | 2 | 199 | | await broadcaster.BroadcastLogAsync(level, message, cancellationToken); |
| | 1 | 200 | | Logger.Debug("Broadcasted log message via SignalR: {Level} - {Message}", level, message); |
| | 1 | 201 | | return true; |
| | | 202 | | } |
| | 1 | 203 | | catch (Exception ex) |
| | | 204 | | { |
| | 1 | 205 | | Logger.Error(ex, "Failed to broadcast log message: {Level} - {Message}", level, message); |
| | 1 | 206 | | return false; |
| | | 207 | | } |
| | 4 | 208 | | } |
| | | 209 | | |
| | | 210 | | /// <summary> |
| | | 211 | | /// Synchronous wrapper for BroadcastLogAsync. |
| | | 212 | | /// </summary> |
| | | 213 | | /// <param name="level">The log level (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 214 | | /// <param name="message">The log message to broadcast.</param> |
| | | 215 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 216 | | /// <returns>True if the log was broadcast successfully; otherwise, false.</returns> |
| | | 217 | | public bool BroadcastLog(string level, string message, CancellationToken cancellationToken = default) => |
| | 0 | 218 | | BroadcastLogAsync(level, message, cancellationToken).GetAwaiter().GetResult(); |
| | | 219 | | |
| | | 220 | | /// <summary> |
| | | 221 | | /// Asynchronously broadcasts a custom event to all connected SignalR clients using the IRealtimeBroadcaster service |
| | | 222 | | /// </summary> |
| | | 223 | | /// <param name="eventName">The event name (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 224 | | /// <param name="data">The event data to broadcast.</param> |
| | | 225 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 226 | | /// <returns>True if the event was broadcast successfully; otherwise, false.</returns> |
| | | 227 | | public async Task<bool> BroadcastEventAsync(string eventName, object? data, CancellationToken cancellationToken = de |
| | | 228 | | { |
| | 1 | 229 | | var svcProvider = HttpContext.RequestServices; |
| | | 230 | | |
| | 1 | 231 | | if (svcProvider == null) |
| | | 232 | | { |
| | 0 | 233 | | Logger.Warning("No service provider available to resolve IRealtimeBroadcaster."); |
| | 0 | 234 | | return false; |
| | | 235 | | } |
| | 1 | 236 | | if (svcProvider.GetService(typeof(IRealtimeBroadcaster)) is not IRealtimeBroadcaster broadcaster) |
| | | 237 | | { |
| | 0 | 238 | | Logger.Warning("IRealtimeBroadcaster service is not registered. Make sure SignalR is configured with Kestrun |
| | 0 | 239 | | return false; |
| | | 240 | | } |
| | | 241 | | try |
| | | 242 | | { |
| | 1 | 243 | | await broadcaster.BroadcastEventAsync(eventName, data, cancellationToken); |
| | 1 | 244 | | Logger.Debug("Broadcasted event via SignalR: {EventName} - {Data}", eventName, data); |
| | 1 | 245 | | return true; |
| | | 246 | | } |
| | 0 | 247 | | catch (Exception ex) |
| | | 248 | | { |
| | 0 | 249 | | Logger.Error(ex, "Failed to broadcast event: {EventName} - {Data}", eventName, data); |
| | 0 | 250 | | return false; |
| | | 251 | | } |
| | 1 | 252 | | } |
| | | 253 | | |
| | | 254 | | /// <summary> |
| | | 255 | | /// Synchronous wrapper for BroadcastEventAsync. |
| | | 256 | | /// </summary> |
| | | 257 | | /// <param name="eventName">The event name (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 258 | | /// <param name="data">The event data to broadcast.</param> |
| | | 259 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 260 | | /// <returns>True if the event was broadcast successfully; otherwise, false.</returns> |
| | | 261 | | public bool BroadcastEvent(string eventName, object? data, CancellationToken cancellationToken = default) => |
| | 0 | 262 | | BroadcastEventAsync(eventName, data, cancellationToken).GetAwaiter().GetResult(); |
| | | 263 | | |
| | | 264 | | /// <summary> |
| | | 265 | | /// Asynchronously broadcasts a message to a specific group of SignalR clients using the IRealtimeBroadcaster servic |
| | | 266 | | /// </summary> |
| | | 267 | | /// <param name="groupName">The name of the group to broadcast the message to.</param> |
| | | 268 | | /// <param name="method">The name of the method to invoke on the client.</param> |
| | | 269 | | /// <param name="message">The message to broadcast.</param> |
| | | 270 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 271 | | /// <returns>True if the message was broadcast successfully; otherwise, false.</returns> |
| | | 272 | | public async Task<bool> BroadcastToGroupAsync(string groupName, string method, object? message, CancellationToken ca |
| | | 273 | | { |
| | 1 | 274 | | var svcProvider = HttpContext.RequestServices; |
| | | 275 | | |
| | 1 | 276 | | if (svcProvider == null) |
| | | 277 | | { |
| | 0 | 278 | | Logger.Warning("No service provider available to resolve IRealtimeBroadcaster."); |
| | 0 | 279 | | return false; |
| | | 280 | | } |
| | 1 | 281 | | if (svcProvider.GetService(typeof(IRealtimeBroadcaster)) is not IRealtimeBroadcaster broadcaster) |
| | | 282 | | { |
| | 0 | 283 | | Logger.Warning("IRealtimeBroadcaster service is not registered. Make sure SignalR is configured with Kestrun |
| | 0 | 284 | | return false; |
| | | 285 | | } |
| | | 286 | | try |
| | | 287 | | { |
| | 1 | 288 | | await broadcaster.BroadcastToGroupAsync(groupName, method, message, cancellationToken); |
| | 1 | 289 | | Logger.Debug("Broadcasted log message to group via SignalR: {GroupName} - {Method} - {Message}", groupName, |
| | 1 | 290 | | return true; |
| | | 291 | | } |
| | 0 | 292 | | catch (Exception ex) |
| | | 293 | | { |
| | 0 | 294 | | Logger.Error(ex, "Failed to broadcast log message: {GroupName} - {Method} - {Message}", groupName, method, m |
| | 0 | 295 | | return false; |
| | | 296 | | } |
| | 1 | 297 | | } |
| | | 298 | | |
| | | 299 | | /// <summary> |
| | | 300 | | /// Synchronous wrapper for BroadcastToGroupAsync. |
| | | 301 | | /// </summary> |
| | | 302 | | /// <param name="groupName">The name of the group to broadcast the message to.</param> |
| | | 303 | | /// <param name="method">The name of the method to invoke on the client.</param> |
| | | 304 | | /// <param name="message">The message to broadcast.</param> |
| | | 305 | | /// <returns>True if the message was broadcast successfully; otherwise, false.</returns> |
| | | 306 | | public bool BroadcastToGroup(string groupName, string method, object? message) => |
| | 0 | 307 | | BroadcastToGroupAsync(groupName, method, message, default).GetAwaiter().GetResult(); |
| | | 308 | | |
| | | 309 | | /// <summary> |
| | | 310 | | /// Synchronous wrapper for HttpContext.ChallengeAsync. |
| | | 311 | | /// </summary> |
| | | 312 | | /// <param name="scheme">The authentication scheme to challenge.</param> |
| | | 313 | | /// <param name="properties">The authentication properties to include in the challenge.</param> |
| | 0 | 314 | | public void Challenge(string? scheme, AuthenticationProperties? properties) => HttpContext.ChallengeAsync(scheme, pr |
| | | 315 | | |
| | | 316 | | /// <summary> |
| | | 317 | | /// Synchronous wrapper for HttpContext.ChallengeAsync using a Hashtable for properties. |
| | | 318 | | /// </summary> |
| | | 319 | | /// <param name="scheme">The authentication scheme to challenge.</param> |
| | | 320 | | /// <param name="properties">The authentication properties to include in the challenge.</param> |
| | | 321 | | public void Challenge(string? scheme, Hashtable? properties) |
| | | 322 | | { |
| | 0 | 323 | | var dict = new Dictionary<string, string?>(); |
| | 0 | 324 | | if (properties != null) |
| | | 325 | | { |
| | 0 | 326 | | foreach (DictionaryEntry entry in properties) |
| | | 327 | | { |
| | 0 | 328 | | dict[entry.Key.ToString()!] = entry.Value?.ToString(); |
| | | 329 | | } |
| | | 330 | | } |
| | 0 | 331 | | AuthenticationProperties authProps = new(dict); |
| | 0 | 332 | | HttpContext.ChallengeAsync(scheme, authProps).GetAwaiter().GetResult(); |
| | 0 | 333 | | } |
| | | 334 | | |
| | | 335 | | /// <summary> |
| | | 336 | | /// Synchronous wrapper for HttpContext.ChallengeAsync using a Dictionary for properties. |
| | | 337 | | /// </summary> |
| | | 338 | | /// <param name="scheme">The authentication scheme to challenge.</param> |
| | | 339 | | /// <param name="properties">The authentication properties to include in the challenge.</param> |
| | | 340 | | public void Challenge(string? scheme, Dictionary<string, string?>? properties) |
| | | 341 | | { |
| | 0 | 342 | | if (properties == null) |
| | | 343 | | { |
| | 0 | 344 | | HttpContext.ChallengeAsync(scheme).GetAwaiter().GetResult(); |
| | 0 | 345 | | return; |
| | | 346 | | } |
| | | 347 | | |
| | 0 | 348 | | AuthenticationProperties authProps = new(properties); |
| | 0 | 349 | | HttpContext.ChallengeAsync(scheme, authProps).GetAwaiter().GetResult(); |
| | 0 | 350 | | } |
| | | 351 | | |
| | | 352 | | /// <summary> |
| | | 353 | | /// Asynchronous wrapper for HttpContext.ChallengeAsync using a Hashtable for properties. |
| | | 354 | | /// </summary> |
| | | 355 | | /// <param name="scheme">The authentication scheme to challenge.</param> |
| | | 356 | | /// <param name="properties">The authentication properties to include in the challenge.</param> |
| | | 357 | | /// <returns>Task representing the asynchronous operation.</returns> |
| | | 358 | | public Task ChallengeAsync(string? scheme, Hashtable? properties) |
| | | 359 | | { |
| | 0 | 360 | | var dict = new Dictionary<string, string?>(); |
| | 0 | 361 | | if (properties != null) |
| | | 362 | | { |
| | 0 | 363 | | foreach (DictionaryEntry entry in properties) |
| | | 364 | | { |
| | 0 | 365 | | dict[entry.Key.ToString()!] = entry.Value?.ToString(); |
| | | 366 | | } |
| | | 367 | | } |
| | 0 | 368 | | AuthenticationProperties authProps = new(dict); |
| | 0 | 369 | | return HttpContext.ChallengeAsync(scheme, authProps); |
| | | 370 | | } |
| | | 371 | | |
| | | 372 | | /// <summary> |
| | | 373 | | /// Synchronous wrapper for HttpContext.SignOutAsync. |
| | | 374 | | /// </summary> |
| | | 375 | | /// <param name="scheme">The authentication scheme to sign out.</param> |
| | 0 | 376 | | public void SignOut(string? scheme) => HttpContext.SignOutAsync(scheme).GetAwaiter().GetResult(); |
| | | 377 | | /// <summary> |
| | | 378 | | /// Synchronous wrapper for HttpContext.SignOutAsync. |
| | | 379 | | /// </summary> |
| | | 380 | | /// <param name="scheme">The authentication scheme to sign out.</param> |
| | | 381 | | /// <param name="properties">The authentication properties to include in the sign-out.</param> |
| | | 382 | | public void SignOut(string? scheme, AuthenticationProperties? properties) |
| | | 383 | | { |
| | 0 | 384 | | HttpContext.SignOutAsync(scheme, properties).GetAwaiter().GetResult(); |
| | 0 | 385 | | if (properties != null && !string.IsNullOrWhiteSpace(properties.RedirectUri)) |
| | | 386 | | { |
| | 0 | 387 | | Response.WriteStatusOnly(302); |
| | | 388 | | } |
| | 0 | 389 | | } |
| | | 390 | | |
| | | 391 | | /// <summary> |
| | | 392 | | /// Synchronous wrapper for HttpContext.SignOutAsync using a Hashtable for properties. |
| | | 393 | | /// </summary> |
| | | 394 | | /// <param name="scheme">The authentication scheme to sign out.</param> |
| | | 395 | | /// <param name="properties">The authentication properties to include in the sign-out.</param> |
| | | 396 | | public void SignOut(string? scheme, Hashtable? properties) |
| | | 397 | | { |
| | 0 | 398 | | AuthenticationProperties? authProps = null; |
| | | 399 | | // Convert Hashtable to Dictionary<string, string?> for AuthenticationProperties |
| | 0 | 400 | | if (properties is not null) |
| | | 401 | | { |
| | 0 | 402 | | var dict = new Dictionary<string, string?>(); |
| | | 403 | | // Convert each entry in the Hashtable to a string key-value pair |
| | 0 | 404 | | foreach (DictionaryEntry entry in properties) |
| | | 405 | | { |
| | 0 | 406 | | dict[entry.Key.ToString()!] = entry.Value?.ToString(); |
| | | 407 | | } |
| | | 408 | | // Create AuthenticationProperties from the dictionary |
| | 0 | 409 | | authProps = new AuthenticationProperties(dict); |
| | | 410 | | } |
| | | 411 | | // Call SignOut with the constructed AuthenticationProperties |
| | 0 | 412 | | SignOut(scheme, authProps); |
| | 0 | 413 | | } |
| | | 414 | | #region Sse Helpers |
| | | 415 | | /// <summary> |
| | | 416 | | /// Starts a Server-Sent Events (SSE) response by setting the appropriate headers. |
| | | 417 | | /// </summary> |
| | | 418 | | public void StartSse() |
| | | 419 | | { |
| | 0 | 420 | | HttpContext.Response.Headers.CacheControl = "no-cache"; |
| | 0 | 421 | | HttpContext.Response.Headers.Connection = "keep-alive"; |
| | 0 | 422 | | HttpContext.Response.Headers["X-Accel-Buffering"] = "no"; // helps with nginx |
| | 0 | 423 | | HttpContext.Response.ContentType = "text/event-stream"; |
| | 0 | 424 | | } |
| | | 425 | | |
| | | 426 | | /// <summary> |
| | | 427 | | /// Writes a Server-Sent Event (SSE) to the response stream. |
| | | 428 | | /// </summary> |
| | | 429 | | /// <param name="event">The event type</param> |
| | | 430 | | /// <param name="data">The data payload of the event</param> |
| | | 431 | | /// <param name="id"> The event ID.</param> |
| | | 432 | | /// <param name="retryMs">Reconnection time in milliseconds</param> |
| | | 433 | | /// <param name="ct">Cancellation token</param> |
| | | 434 | | /// <returns> Task representing the asynchronous write operation.</returns> |
| | | 435 | | public async Task WriteSseEventAsync( |
| | | 436 | | string? @event, |
| | | 437 | | string data, |
| | | 438 | | string? id = null, |
| | | 439 | | int? retryMs = null, |
| | | 440 | | CancellationToken ct = default) |
| | | 441 | | { |
| | | 442 | | // SSE fields are line based |
| | 0 | 443 | | if (retryMs is not null) |
| | | 444 | | { |
| | 0 | 445 | | await HttpContext.Response.WriteAsync($"retry: {retryMs}\n", ct); |
| | | 446 | | } |
| | | 447 | | |
| | 0 | 448 | | if (id is not null) |
| | | 449 | | { |
| | 0 | 450 | | await HttpContext.Response.WriteAsync($"id: {id}\n", ct); |
| | | 451 | | } |
| | | 452 | | |
| | 0 | 453 | | if (!string.IsNullOrWhiteSpace(@event)) |
| | | 454 | | { |
| | 0 | 455 | | await HttpContext.Response.WriteAsync($"event: {@event}\n", ct); |
| | | 456 | | } |
| | | 457 | | |
| | | 458 | | // data can be multi-line; each line must be prefixed with "data: " |
| | 0 | 459 | | using (var sr = new StringReader(data)) |
| | | 460 | | { |
| | | 461 | | string? line; |
| | 0 | 462 | | while ((line = sr.ReadLine()) is not null) |
| | | 463 | | { |
| | 0 | 464 | | await HttpContext.Response.WriteAsync($"data: {line}\n", ct); |
| | | 465 | | } |
| | 0 | 466 | | } |
| | | 467 | | |
| | 0 | 468 | | await HttpContext.Response.WriteAsync("\n", ct); // end of event |
| | 0 | 469 | | await HttpContext.Response.Body.FlushAsync(ct); // important! |
| | 0 | 470 | | } |
| | | 471 | | |
| | | 472 | | /// <summary> |
| | | 473 | | /// Synchronous wrapper for WriteSseEventAsync. |
| | | 474 | | /// </summary> |
| | | 475 | | /// <param name="event">The name of the event.</param> |
| | | 476 | | /// <param name="data">The data payload of the event.</param> |
| | | 477 | | /// <param name="id"> The event ID.</param> |
| | | 478 | | /// <param name="retryMs">Reconnection time in milliseconds</param> |
| | | 479 | | public void WriteSseEvent( |
| | | 480 | | string? @event, string data, string? id = null, int? retryMs = null) => |
| | 0 | 481 | | WriteSseEventAsync(@event, data, id, retryMs, CancellationToken.None).GetAwaiter().GetResult(); |
| | | 482 | | |
| | | 483 | | #endregion |
| | | 484 | | } |