| | | 1 | | |
| | | 2 | | using System.Diagnostics.CodeAnalysis; |
| | | 3 | | using System.Xml.Linq; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | using System.Text.Json.Serialization; |
| | | 6 | | using Kestrun.Utilities.Json; |
| | | 7 | | using Microsoft.AspNetCore.StaticFiles; |
| | | 8 | | using System.Text; |
| | | 9 | | using Serilog.Events; |
| | | 10 | | using System.Buffers; |
| | | 11 | | using Microsoft.Extensions.FileProviders; |
| | | 12 | | using Microsoft.AspNetCore.WebUtilities; |
| | | 13 | | using System.Net; |
| | | 14 | | using MongoDB.Bson; |
| | | 15 | | using Kestrun.Utilities; |
| | | 16 | | using System.Collections; |
| | | 17 | | using CsvHelper.Configuration; |
| | | 18 | | using System.Globalization; |
| | | 19 | | using CsvHelper; |
| | | 20 | | using System.Reflection; |
| | | 21 | | using Microsoft.Net.Http.Headers; |
| | | 22 | | using Kestrun.Utilities.Yaml; |
| | | 23 | | using Kestrun.Hosting.Options; |
| | | 24 | | using Kestrun.Callback; |
| | | 25 | | using System.Management.Automation; |
| | | 26 | | using Kestrun.Logging; |
| | | 27 | | |
| | | 28 | | namespace Kestrun.Models; |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Represents an HTTP response in the Kestrun framework, providing methods to write various content types and manage he |
| | | 32 | | /// </summary> |
| | | 33 | | /// <remarks> |
| | | 34 | | /// Initializes a new instance of the <see cref="KestrunResponse"/> class with the specified request and optional body a |
| | | 35 | | /// </remarks> |
| | | 36 | | public class KestrunResponse |
| | | 37 | | { |
| | 1 | 38 | | private static readonly ContentTypeWithSchema[] LegacyNegotiatedResponseContentTypes = |
| | 1 | 39 | | [ |
| | 1 | 40 | | new("*/*") |
| | 1 | 41 | | ]; |
| | | 42 | | |
| | | 43 | | /// <summary> |
| | | 44 | | /// Flag indicating whether callbacks have already been enqueued. |
| | | 45 | | /// </summary> |
| | | 46 | | internal int CallbacksEnqueuedFlag; // 0 = no, 1 = yes |
| | | 47 | | |
| | | 48 | | /// <summary> |
| | | 49 | | /// Gets the list of callback requests associated with this response. |
| | | 50 | | /// </summary> |
| | 211 | 51 | | public List<CallBackExecutionPlan> CallbackPlan { get; } = []; |
| | | 52 | | |
| | 495 | 53 | | private Serilog.ILogger Logger => KrContext.Host.Logger; |
| | | 54 | | /// <summary> |
| | | 55 | | /// Gets the route options associated with this response. |
| | | 56 | | /// </summary> |
| | 15 | 57 | | public MapRouteOptions MapRouteOptions => KrContext.MapRouteOptions; |
| | | 58 | | /// <summary> |
| | | 59 | | /// Gets the associated KestrunContext for this response. |
| | | 60 | | /// </summary> |
| | 1214 | 61 | | public required KestrunContext KrContext { get; init; } |
| | | 62 | | |
| | | 63 | | /// <summary> |
| | | 64 | | /// Gets the KestrunHost associated with this response. |
| | | 65 | | /// </summary> |
| | 0 | 66 | | public Hosting.KestrunHost Host => KrContext.Host; |
| | | 67 | | /// <summary> |
| | | 68 | | /// A set of MIME types that are considered text-based for response content. |
| | | 69 | | /// </summary> |
| | 1 | 70 | | public static readonly HashSet<string> TextBasedMimeTypes = |
| | 1 | 71 | | #pragma warning disable IDE0028 // Simplify collection initialization |
| | 1 | 72 | | new(StringComparer.OrdinalIgnoreCase) |
| | 1 | 73 | | #pragma warning restore IDE0028 // Simplify collection initialization |
| | 1 | 74 | | { |
| | 1 | 75 | | "application/json", |
| | 1 | 76 | | "application/xml", |
| | 1 | 77 | | "application/javascript", |
| | 1 | 78 | | "application/xhtml+xml", |
| | 1 | 79 | | "application/x-www-form-urlencoded", |
| | 1 | 80 | | "application/yaml", |
| | 1 | 81 | | "application/graphql" |
| | 1 | 82 | | }; |
| | | 83 | | |
| | | 84 | | /// <summary> |
| | | 85 | | /// Initializes a new instance of the <see cref="KestrunResponse"/> class. |
| | | 86 | | /// </summary> |
| | | 87 | | /// <param name="krContext">The associated <see cref="KestrunContext"/> for this response.</param> |
| | | 88 | | /// <param name="bodyAsyncThreshold">The threshold in bytes for using async body write operations. Defaults to 8192. |
| | | 89 | | [SetsRequiredMembers] |
| | 175 | 90 | | public KestrunResponse(KestrunContext krContext, int bodyAsyncThreshold = 8192) |
| | | 91 | | { |
| | 175 | 92 | | KrContext = krContext; |
| | 175 | 93 | | BodyAsyncThreshold = bodyAsyncThreshold; |
| | 175 | 94 | | Request = KrContext.Request ?? throw new ArgumentNullException(nameof(KrContext)); |
| | 175 | 95 | | AcceptCharset = KrContext.Request.Headers.TryGetValue("Accept-Charset", out var value) ? Encoding.GetEncoding(va |
| | 175 | 96 | | StatusCode = KrContext.HttpContext.Response.StatusCode; |
| | 175 | 97 | | } |
| | | 98 | | |
| | | 99 | | /// <summary> |
| | | 100 | | /// Gets the <see cref="HttpContext"/> associated with the response. |
| | | 101 | | /// </summary> |
| | 0 | 102 | | public HttpContext Context => KrContext.HttpContext; |
| | | 103 | | /// <summary> |
| | | 104 | | /// Gets or sets the HTTP status code for the response. |
| | | 105 | | /// </summary> |
| | 358 | 106 | | public int StatusCode { get; set; } |
| | | 107 | | /// <summary> |
| | | 108 | | /// Gets or sets the collection of HTTP headers for the response. |
| | | 109 | | /// </summary> |
| | 253 | 110 | | public Dictionary<string, string> Headers { get; set; } = []; |
| | | 111 | | /// <summary> |
| | | 112 | | /// Gets or sets the MIME content type of the response. |
| | | 113 | | /// </summary> |
| | 469 | 114 | | public string? ContentType { get; set; } = "text/plain"; |
| | | 115 | | /// <summary> |
| | | 116 | | /// Gets or sets the body of the response, which can be a string, byte array, stream, or file info. |
| | | 117 | | /// </summary> |
| | 254 | 118 | | public object? Body { get; set; } |
| | | 119 | | /// <summary> |
| | | 120 | | /// Gets or sets the URL to redirect the response to, if an HTTP redirect is required. |
| | | 121 | | /// </summary> |
| | 67 | 122 | | public string? RedirectUrl { get; set; } // For HTTP redirects |
| | | 123 | | /// <summary> |
| | | 124 | | /// Gets or sets the list of Set-Cookie header values for the response. |
| | | 125 | | /// </summary> |
| | 35 | 126 | | public List<string>? Cookies { get; set; } // For Set-Cookie headers |
| | | 127 | | |
| | | 128 | | /// <summary> |
| | | 129 | | /// Text encoding for textual MIME types. |
| | | 130 | | /// </summary> |
| | 221 | 131 | | public Encoding Encoding { get; set; } = Encoding.UTF8; |
| | | 132 | | |
| | | 133 | | /// <summary> |
| | | 134 | | /// Content-Disposition header value. |
| | | 135 | | /// </summary> |
| | 218 | 136 | | public ContentDispositionOptions ContentDisposition { get; set; } = new ContentDispositionOptions(); |
| | | 137 | | /// <summary> |
| | | 138 | | /// Gets the associated KestrunRequest for this response. |
| | | 139 | | /// </summary> |
| | 235 | 140 | | public required KestrunRequest Request { get; init; } |
| | | 141 | | |
| | | 142 | | /// <summary> |
| | | 143 | | /// Global text encoding for all responses. Defaults to UTF-8. |
| | | 144 | | /// </summary> |
| | 206 | 145 | | public required Encoding AcceptCharset { get; init; } |
| | | 146 | | |
| | | 147 | | /// <summary> |
| | | 148 | | /// If the response body is larger than this threshold (in bytes), async write will be used. |
| | | 149 | | /// </summary> |
| | 175 | 150 | | public required int BodyAsyncThreshold { get; init; } |
| | | 151 | | |
| | | 152 | | /// <summary> |
| | | 153 | | /// Cache-Control header value for the response. |
| | | 154 | | /// </summary> |
| | 35 | 155 | | public CacheControlHeaderValue? CacheControl { get; set; } |
| | | 156 | | |
| | | 157 | | /// <summary> |
| | | 158 | | /// Represents a simple object for writing responses with a value and status code. |
| | | 159 | | /// </summary> |
| | | 160 | | /// <param name="Value">The value to be written in the response.</param> |
| | | 161 | | /// <param name="Status">The HTTP status code for the response.</param> |
| | | 162 | | /// <param name="Error">An optional error code to include in the response.</param> |
| | 202 | 163 | | public record WriteObject(object? Value, int Status = StatusCodes.Status200OK, int? Error = null); |
| | | 164 | | |
| | | 165 | | /// <summary> |
| | | 166 | | /// Gets or sets a postponed write object that can be used for deferred response writing, allowing the response to b |
| | | 167 | | /// </summary> |
| | 199 | 168 | | public WriteObject PostPonedWriteObject { get; set; } = new WriteObject(null, StatusCodes.Status200OK); |
| | | 169 | | |
| | | 170 | | /// <summary> |
| | | 171 | | /// Indicates whether there is a postponed write object with a non-null value, which can be used to determine if a d |
| | | 172 | | /// </summary> |
| | 2 | 173 | | public bool HasPostPonedWriteObject => PostPonedWriteObject.Value is not null; |
| | | 174 | | #region Constructors |
| | | 175 | | #endregion |
| | | 176 | | |
| | | 177 | | #region Helpers |
| | | 178 | | private static string GetSafeCurrentDirectoryOrBaseDirectory() |
| | | 179 | | { |
| | | 180 | | try |
| | | 181 | | { |
| | 2 | 182 | | return Directory.GetCurrentDirectory(); |
| | | 183 | | } |
| | 0 | 184 | | catch (Exception ex) when (ex is IOException |
| | 0 | 185 | | or UnauthorizedAccessException |
| | 0 | 186 | | or DirectoryNotFoundException |
| | 0 | 187 | | or FileNotFoundException) |
| | | 188 | | { |
| | | 189 | | // On Unix/macOS, getcwd() can throw if the process CWD was deleted. |
| | | 190 | | // We use AppContext.BaseDirectory as a stable fallback to avoid crashing in diagnostics |
| | | 191 | | // and when resolving relative paths. |
| | 0 | 192 | | return AppContext.BaseDirectory; |
| | | 193 | | } |
| | 2 | 194 | | } |
| | | 195 | | |
| | 2 | 196 | | private static string GetSafeCurrentDirectoryForLogging() => GetSafeCurrentDirectoryOrBaseDirectory(); |
| | | 197 | | |
| | | 198 | | /// <summary> |
| | | 199 | | /// Retrieves the value of the specified header from the response headers. |
| | | 200 | | /// </summary> |
| | | 201 | | /// <param name="key">The name of the header to retrieve.</param> |
| | | 202 | | /// <returns>The value of the header if found; otherwise, null.</returns> |
| | 0 | 203 | | public string? GetHeader(string key) => Headers.TryGetValue(key, out var value) ? value : null; |
| | | 204 | | |
| | | 205 | | /// <summary> |
| | | 206 | | /// Determines whether the specified content type is text-based or supports a charset. |
| | | 207 | | /// </summary> |
| | | 208 | | /// <param name="type">The MIME content type to check.</param> |
| | | 209 | | /// <returns>True if the content type is text-based; otherwise, false.</returns> |
| | | 210 | | public bool IsTextBasedContentType(string type) |
| | | 211 | | { |
| | 37 | 212 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 213 | | { |
| | 27 | 214 | | Logger.Debug("Checking if content type is text-based: {ContentType}", type); |
| | | 215 | | } |
| | | 216 | | |
| | | 217 | | // Check if the content type is text-based or has a charset |
| | 37 | 218 | | if (string.IsNullOrEmpty(type)) |
| | | 219 | | { |
| | 1 | 220 | | return false; |
| | | 221 | | } |
| | | 222 | | |
| | 36 | 223 | | if (type.StartsWith("text/", StringComparison.OrdinalIgnoreCase)) |
| | | 224 | | { |
| | 21 | 225 | | return true; |
| | | 226 | | } |
| | 15 | 227 | | if (type == "application/x-www-form-urlencoded") |
| | | 228 | | { |
| | 0 | 229 | | return true; |
| | | 230 | | } |
| | | 231 | | |
| | | 232 | | // Include structured types using XML or JSON suffixes |
| | 15 | 233 | | if (type.EndsWith("xml", StringComparison.OrdinalIgnoreCase) || |
| | 15 | 234 | | type.EndsWith("json", StringComparison.OrdinalIgnoreCase) || |
| | 15 | 235 | | type.EndsWith("yaml", StringComparison.OrdinalIgnoreCase) || |
| | 15 | 236 | | type.EndsWith("csv", StringComparison.OrdinalIgnoreCase)) |
| | | 237 | | { |
| | 4 | 238 | | return true; |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | // Common application types where charset makes sense |
| | 11 | 242 | | return TextBasedMimeTypes.Contains(type); |
| | | 243 | | } |
| | | 244 | | /// <summary> |
| | | 245 | | /// Adds callback parameters for the specified callback ID, body, and parameters. |
| | | 246 | | /// </summary> |
| | | 247 | | /// <param name="callbackId">The identifier for the callback</param> |
| | | 248 | | /// <param name="bodyParameterName">The name of the body parameter, if any</param> |
| | | 249 | | /// <param name="parameters">The parameters for the callback</param> |
| | | 250 | | public void AddCallbackParameters(string callbackId, string? bodyParameterName, Dictionary<string, object?> paramete |
| | | 251 | | { |
| | 0 | 252 | | if (MapRouteOptions.CallbackPlan is null || MapRouteOptions.CallbackPlan.Count == 0) |
| | | 253 | | { |
| | 0 | 254 | | return; |
| | | 255 | | } |
| | 0 | 256 | | var plan = MapRouteOptions.CallbackPlan.FirstOrDefault(p => p.CallbackId == callbackId); |
| | 0 | 257 | | if (plan is null) |
| | | 258 | | { |
| | 0 | 259 | | Logger.Warning("CallbackPlan '{id}' not found.", callbackId); |
| | 0 | 260 | | return; |
| | | 261 | | } |
| | | 262 | | // Create a new execution plan |
| | 0 | 263 | | var newExecutionPlan = new CallBackExecutionPlan( |
| | 0 | 264 | | CallbackId: callbackId, |
| | 0 | 265 | | Plan: plan, |
| | 0 | 266 | | BodyParameterName: bodyParameterName, |
| | 0 | 267 | | Parameters: parameters |
| | 0 | 268 | | ); |
| | | 269 | | |
| | 0 | 270 | | CallbackPlan.Add(newExecutionPlan); |
| | 0 | 271 | | } |
| | | 272 | | #endregion |
| | | 273 | | |
| | | 274 | | #region Response Writers |
| | | 275 | | /// <summary> |
| | | 276 | | /// Writes a file response with the specified file path, content type, and HTTP status code. |
| | | 277 | | /// </summary> |
| | | 278 | | /// <param name="filePath">The path to the file to be sent in the response.</param> |
| | | 279 | | /// <param name="contentType">The MIME type of the file content.</param> |
| | | 280 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 281 | | public void WriteFileResponse( |
| | | 282 | | string? filePath, |
| | | 283 | | string? contentType, |
| | | 284 | | int statusCode = StatusCodes.Status200OK |
| | | 285 | | ) |
| | | 286 | | { |
| | 2 | 287 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 288 | | { |
| | 2 | 289 | | Logger.Debug("Writing file response,FilePath={FilePath} StatusCode={StatusCode}, ContentType={ContentType}, |
| | 2 | 290 | | filePath, statusCode, contentType, GetSafeCurrentDirectoryForLogging()); |
| | | 291 | | } |
| | | 292 | | |
| | 2 | 293 | | if (string.IsNullOrEmpty(filePath)) |
| | | 294 | | { |
| | 0 | 295 | | throw new ArgumentException("File path cannot be null or empty.", nameof(filePath)); |
| | | 296 | | } |
| | | 297 | | |
| | | 298 | | // IMPORTANT: |
| | | 299 | | // - Path.GetFullPath(relative) uses the process CWD. |
| | | 300 | | // - If the CWD is missing/deleted (can occur in CI/test scenarios), GetFullPath can fail. |
| | | 301 | | // Resolve relative paths against a safe, existing base directory instead. |
| | 2 | 302 | | var fullPath = Path.IsPathRooted(filePath) |
| | 2 | 303 | | ? Path.GetFullPath(filePath) |
| | 2 | 304 | | : Path.GetFullPath(filePath, GetSafeCurrentDirectoryOrBaseDirectory()); |
| | | 305 | | |
| | 2 | 306 | | if (!File.Exists(fullPath)) |
| | | 307 | | { |
| | 1 | 308 | | StatusCode = StatusCodes.Status404NotFound; |
| | 1 | 309 | | Body = $"File not found: {filePath}"; |
| | 1 | 310 | | ContentType = $"text/plain; charset={Encoding.WebName}"; |
| | 1 | 311 | | return; |
| | | 312 | | } |
| | | 313 | | |
| | | 314 | | // 2. Extract the directory to use as the "root" |
| | 1 | 315 | | var directory = Path.GetDirectoryName(fullPath) |
| | 1 | 316 | | ?? throw new InvalidOperationException("Could not determine directory from file path"); |
| | | 317 | | |
| | 1 | 318 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 319 | | { |
| | 1 | 320 | | Logger.Debug("Serving file: {FilePath}", fullPath); |
| | | 321 | | } |
| | | 322 | | |
| | | 323 | | // Create a physical file provider for the directory |
| | 1 | 324 | | var physicalProvider = new PhysicalFileProvider(directory); |
| | 1 | 325 | | var fi = physicalProvider.GetFileInfo(Path.GetFileName(fullPath)); |
| | 1 | 326 | | var provider = new FileExtensionContentTypeProvider(); |
| | 1 | 327 | | contentType ??= provider.TryGetContentType(fullPath, out var ct) |
| | 1 | 328 | | ? ct |
| | 1 | 329 | | : "application/octet-stream"; |
| | 1 | 330 | | Body = fi; |
| | | 331 | | |
| | | 332 | | // headers & metadata |
| | 1 | 333 | | StatusCode = statusCode; |
| | 1 | 334 | | ContentType = contentType; |
| | 1 | 335 | | Logger.Debug("File response prepared: FileName={FileName}, Length={Length}, ContentType={ContentType}", |
| | 1 | 336 | | fi.Name, fi.Length, ContentType); |
| | 1 | 337 | | } |
| | | 338 | | |
| | | 339 | | /// <summary> |
| | | 340 | | /// Writes a JSON response with the specified input object and HTTP status code. |
| | | 341 | | /// </summary> |
| | | 342 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 343 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | 8 | 344 | | public void WriteJsonResponse(object? inputObject, int statusCode = StatusCodes.Status200OK) => WriteJsonResponseAsy |
| | | 345 | | |
| | | 346 | | /// <summary> |
| | | 347 | | /// Asynchronously writes a JSON response with the specified input object and HTTP status code. |
| | | 348 | | /// </summary> |
| | | 349 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 350 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 351 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 12 | 352 | | public async Task WriteJsonResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? cont |
| | | 353 | | |
| | | 354 | | /// <summary> |
| | | 355 | | /// Writes a JSON response using the specified input object and serializer settings. |
| | | 356 | | /// </summary> |
| | | 357 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 358 | | /// <param name="serializerOptions">The options to use for JSON serialization.</param> |
| | | 359 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 360 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 0 | 361 | | public void WriteJsonResponse(object? inputObject, JsonSerializerOptions serializerOptions, int statusCode = StatusC |
| | | 362 | | |
| | | 363 | | /// <summary> |
| | | 364 | | /// Asynchronously writes a JSON response using the specified input object and serializer settings. |
| | | 365 | | /// </summary> |
| | | 366 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 367 | | /// <param name="serializerOptions">The options to use for JSON serialization.</param> |
| | | 368 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 369 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 370 | | public async Task WriteJsonResponseAsync(object? inputObject, JsonSerializerOptions serializerOptions, int statusCod |
| | | 371 | | { |
| | 24 | 372 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 373 | | { |
| | 19 | 374 | | Logger.Debug("Writing JSON response (async), StatusCode={StatusCode}, ContentType={ContentType}", statusCode |
| | | 375 | | } |
| | | 376 | | |
| | 24 | 377 | | ArgumentNullException.ThrowIfNull(serializerOptions); |
| | | 378 | | |
| | 24 | 379 | | var sanitizedPayload = PayloadSanitizer.Sanitize(inputObject); |
| | 48 | 380 | | Body = await Task.Run(() => JsonSerializer.Serialize(sanitizedPayload, serializerOptions)); |
| | 24 | 381 | | ContentType = string.IsNullOrEmpty(contentType) ? $"application/json; charset={Encoding.WebName}" : contentType; |
| | 24 | 382 | | StatusCode = statusCode; |
| | 24 | 383 | | } |
| | | 384 | | /// <summary> |
| | | 385 | | /// Writes a JSON response with the specified input object, serialization depth, compression option, status code, an |
| | | 386 | | /// </summary> |
| | | 387 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 388 | | /// <param name="depth">The maximum depth for JSON serialization.</param> |
| | | 389 | | /// <param name="compress">Whether to compress the JSON output (no indentation).</param> |
| | | 390 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 391 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 1 | 392 | | public void WriteJsonResponse(object? inputObject, int depth, bool compress, int statusCode = StatusCodes.Status200O |
| | | 393 | | |
| | | 394 | | /// <summary> |
| | | 395 | | /// Asynchronously writes a JSON response with the specified input object, serialization depth, compression option, |
| | | 396 | | /// </summary> |
| | | 397 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 398 | | /// <param name="depth">The maximum depth for JSON serialization.</param> |
| | | 399 | | /// <param name="compress">Whether to compress the JSON output (no indentation).</param> |
| | | 400 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 401 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 402 | | public async Task WriteJsonResponseAsync(object? inputObject, int depth, bool compress, int statusCode = StatusCodes |
| | | 403 | | { |
| | 24 | 404 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 405 | | { |
| | 19 | 406 | | Logger.Debug("Writing JSON response (async), StatusCode={StatusCode}, ContentType={ContentType}, Depth={Dept |
| | 19 | 407 | | statusCode, contentType, depth, compress); |
| | | 408 | | } |
| | | 409 | | |
| | 24 | 410 | | var serializerOptions = new JsonSerializerOptions |
| | 24 | 411 | | { |
| | 24 | 412 | | WriteIndented = !compress, |
| | 24 | 413 | | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 24 | 414 | | DictionaryKeyPolicy = JsonNamingPolicy.CamelCase, |
| | 24 | 415 | | ReferenceHandler = ReferenceHandler.IgnoreCycles, |
| | 24 | 416 | | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, |
| | 24 | 417 | | MaxDepth = depth |
| | 24 | 418 | | }; |
| | | 419 | | |
| | 24 | 420 | | await WriteJsonResponseAsync(inputObject, serializerOptions: serializerOptions, statusCode: statusCode, contentT |
| | 24 | 421 | | } |
| | | 422 | | /// <summary> |
| | | 423 | | /// Writes a CBOR response (binary, efficient, not human-readable). |
| | | 424 | | /// </summary> |
| | | 425 | | public async Task WriteCborResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? cont |
| | | 426 | | { |
| | 2 | 427 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 428 | | { |
| | 2 | 429 | | Logger.Debug("Writing CBOR response, StatusCode={StatusCode}, ContentType={ContentType}", statusCode, conten |
| | | 430 | | } |
| | | 431 | | |
| | | 432 | | // Serialize to CBOR using PeterO.Cbor |
| | 4 | 433 | | Body = await Task.Run(() => inputObject != null |
| | 4 | 434 | | ? PeterO.Cbor.CBORObject.FromObject(inputObject).EncodeToBytes() |
| | 4 | 435 | | : []); |
| | 2 | 436 | | ContentType = string.IsNullOrEmpty(contentType) ? "application/cbor" : contentType; |
| | 2 | 437 | | StatusCode = statusCode; |
| | 2 | 438 | | } |
| | | 439 | | |
| | | 440 | | /// <summary> |
| | | 441 | | /// Writes a CBOR response (binary, efficient, not human-readable). |
| | | 442 | | /// </summary> |
| | | 443 | | /// <param name="inputObject">The object to be converted to CBOR.</param> |
| | | 444 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 445 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 0 | 446 | | public void WriteCborResponse(object? inputObject, int statusCode = StatusCodes.Status200OK, string? contentType = n |
| | | 447 | | |
| | | 448 | | /// <summary> |
| | | 449 | | /// Asynchronously writes a BSON response with the specified input object, status code, and content type. |
| | | 450 | | /// </summary> |
| | | 451 | | /// <param name="inputObject">The object to be converted to BSON.</param> |
| | | 452 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 453 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 454 | | public async Task WriteBsonResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? cont |
| | | 455 | | { |
| | 1 | 456 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 457 | | { |
| | 1 | 458 | | Logger.Debug("Writing BSON response, StatusCode={StatusCode}, ContentType={ContentType}", statusCode, conten |
| | | 459 | | } |
| | | 460 | | |
| | | 461 | | // Serialize to BSON (as byte[]) |
| | 2 | 462 | | Body = await Task.Run(() => inputObject != null ? inputObject.ToBson() : []); |
| | 1 | 463 | | ContentType = string.IsNullOrEmpty(contentType) ? "application/bson" : contentType; |
| | 1 | 464 | | StatusCode = statusCode; |
| | 1 | 465 | | } |
| | | 466 | | |
| | | 467 | | /// <summary> |
| | | 468 | | /// Writes a BSON response with the specified input object, status code, and content type. |
| | | 469 | | /// </summary> |
| | | 470 | | /// <param name="inputObject">The object to be converted to BSON.</param> |
| | | 471 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 472 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 0 | 473 | | public void WriteBsonResponse(object? inputObject, int statusCode = StatusCodes.Status200OK, string? contentType = n |
| | | 474 | | |
| | | 475 | | /// <summary> |
| | | 476 | | /// Writes a response with the specified input object and HTTP status code. |
| | | 477 | | /// Chooses the response format based on the Accept header or defaults to text/plain. |
| | | 478 | | /// </summary> |
| | | 479 | | /// <param name="inputObject">The object to be sent in the response body.</param> |
| | | 480 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | 1 | 481 | | public void WriteResponse(object? inputObject, int statusCode = StatusCodes.Status200OK) => WriteResponseAsync(input |
| | | 482 | | |
| | | 483 | | /// <summary> |
| | | 484 | | /// Asynchronously writes a response with the specified input object and HTTP status code. |
| | | 485 | | /// </summary> |
| | | 486 | | /// <param name="inputObject">The object to be sent in the response body.</param> |
| | | 487 | | /// <returns>A task that represents the asynchronous write operation.</returns> |
| | | 488 | | public Task WriteResponseAsync(WriteObject inputObject) |
| | | 489 | | { |
| | 1 | 490 | | ArgumentNullException.ThrowIfNull(inputObject); |
| | | 491 | | |
| | 1 | 492 | | if (inputObject.Value is null) |
| | | 493 | | { |
| | 1 | 494 | | Body = null; |
| | 1 | 495 | | StatusCode = inputObject.Status; |
| | 1 | 496 | | return Task.CompletedTask; |
| | | 497 | | } |
| | | 498 | | |
| | 0 | 499 | | return WriteResponseAsync(inputObject.Value, inputObject.Status); |
| | | 500 | | } |
| | | 501 | | |
| | | 502 | | /// <summary> |
| | | 503 | | /// Asynchronously writes a response with the specified input object and HTTP status code. |
| | | 504 | | /// Chooses the response format based on the Accept header or defaults to text/plain. |
| | | 505 | | /// </summary> |
| | | 506 | | /// <param name="inputObject">The object to be sent in the response body.</param> |
| | | 507 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 508 | | /// <returns>A task that represents the asynchronous write operation.</returns> |
| | | 509 | | public async Task WriteResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK) |
| | | 510 | | { |
| | 13 | 511 | | if (inputObject is null) |
| | | 512 | | { |
| | 2 | 513 | | throw new ArgumentNullException(nameof(inputObject), "Input object cannot be null. Use WriteResponseAsync(Wr |
| | | 514 | | } |
| | | 515 | | |
| | 11 | 516 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 517 | | { |
| | 11 | 518 | | Logger.Debug("Writing response, StatusCode={StatusCode}", statusCode); |
| | | 519 | | } |
| | | 520 | | |
| | 11 | 521 | | Body = inputObject; |
| | | 522 | | |
| | | 523 | | try |
| | | 524 | | { |
| | | 525 | | // Read Accept header (may be missing) |
| | 11 | 526 | | string? acceptHeader = null; |
| | 11 | 527 | | _ = Request?.Headers.TryGetValue(HeaderNames.Accept, out acceptHeader); |
| | | 528 | | |
| | 11 | 529 | | if (!ShouldEnforceOpenApiResponseContentTypes()) |
| | | 530 | | { |
| | 8 | 531 | | await WriteLegacyNegotiatedResponseAsync(inputObject, statusCode, acceptHeader); |
| | 8 | 532 | | return; |
| | | 533 | | } |
| | | 534 | | |
| | 3 | 535 | | await WriteOpenApiNegotiatedResponseAsync(inputObject, statusCode, acceptHeader); |
| | 3 | 536 | | } |
| | 0 | 537 | | catch (Exception ex) |
| | | 538 | | { |
| | 0 | 539 | | Logger.Error(ex, "Error in WriteResponseAsync"); |
| | 0 | 540 | | await WriteErrorResponseAsync("Internal server error.", StatusCodes.Status500InternalServerError); |
| | | 541 | | } |
| | 11 | 542 | | } |
| | | 543 | | |
| | | 544 | | /// <summary> |
| | | 545 | | /// Writes a response using legacy Accept-header negotiation for non-OpenAPI routes. |
| | | 546 | | /// </summary> |
| | | 547 | | /// <param name="inputObject">The response payload.</param> |
| | | 548 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 549 | | /// <param name="acceptHeader">The incoming Accept header value.</param> |
| | | 550 | | /// <returns>A task representing the asynchronous write operation.</returns> |
| | | 551 | | private async Task WriteLegacyNegotiatedResponseAsync(object inputObject, int statusCode, string? acceptHeader) |
| | | 552 | | { |
| | 8 | 553 | | var negotiated = SelectResponseMediaType(acceptHeader, LegacyNegotiatedResponseContentTypes, defaultType: "text/ |
| | 8 | 554 | | ?? new ContentTypeWithSchema("text/plain", null); |
| | | 555 | | |
| | 8 | 556 | | if (Logger.IsEnabled(LogEventLevel.Verbose)) |
| | | 557 | | { |
| | 0 | 558 | | Logger.Verbose( |
| | 0 | 559 | | "Selected legacy response media type for status code: {StatusCode}, MediaType={MediaType}, Accept={Accep |
| | 0 | 560 | | statusCode, |
| | 0 | 561 | | negotiated, |
| | 0 | 562 | | acceptHeader); |
| | | 563 | | } |
| | | 564 | | |
| | 8 | 565 | | await WriteByMediaTypeAsync(negotiated.ContentType, inputObject, statusCode); |
| | 8 | 566 | | } |
| | | 567 | | |
| | | 568 | | /// <summary> |
| | | 569 | | /// Writes a response using OpenAPI-declared response content types for the current status code. |
| | | 570 | | /// </summary> |
| | | 571 | | /// <param name="inputObject">The response payload.</param> |
| | | 572 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 573 | | /// <param name="acceptHeader">The incoming Accept header value.</param> |
| | | 574 | | /// <returns>A task representing the asynchronous write operation.</returns> |
| | | 575 | | private async Task WriteOpenApiNegotiatedResponseAsync(object inputObject, int statusCode, string? acceptHeader) |
| | | 576 | | { |
| | 3 | 577 | | if (!TryGetResponseContentTypes(KrContext.MapRouteOptions.DefaultResponseContentType, statusCode, out var values |
| | | 578 | | { |
| | 1 | 579 | | var msg = $"No default response content type configured for status code {statusCode} and no range/default fa |
| | 1 | 580 | | Logger.Warning(msg); |
| | | 581 | | |
| | 1 | 582 | | await WriteErrorResponseAsync(msg, StatusCodes.Status406NotAcceptable); |
| | 1 | 583 | | return; |
| | | 584 | | } |
| | | 585 | | |
| | 2 | 586 | | if (values.Count == 0) |
| | | 587 | | { |
| | 2 | 588 | | var msg = $"Response status code {statusCode} is declared without content in OpenAPI. Returning a payload fo |
| | 2 | 589 | | Logger.Warning(msg); |
| | 2 | 590 | | await WriteErrorResponseAsync(msg, StatusCodes.Status500InternalServerError); |
| | 2 | 591 | | return; |
| | | 592 | | } |
| | | 593 | | |
| | 0 | 594 | | var supported = values as IReadOnlyList<ContentTypeWithSchema> ?? [.. values]; |
| | | 595 | | |
| | 0 | 596 | | var mediaType = SelectResponseMediaType(acceptHeader, supported, defaultType: supported[0].ContentType); |
| | 0 | 597 | | if (mediaType is null) |
| | | 598 | | { |
| | | 599 | | var supportedMediaTypes = string.Join(", ", supported.Select(x => x.ContentType)); |
| | 0 | 600 | | var msg = $"No supported media type found for status code {statusCode} with Accept header '{acceptHeader}'. |
| | 0 | 601 | | Logger.Warning( |
| | 0 | 602 | | "No supported media type found for status code {StatusCode} with Accept header '{AcceptHeader}'. Support |
| | 0 | 603 | | statusCode, |
| | 0 | 604 | | acceptHeader, |
| | 0 | 605 | | supportedMediaTypes, |
| | 0 | 606 | | supported); |
| | | 607 | | |
| | 0 | 608 | | await WriteErrorResponseAsync(msg, StatusCodes.Status406NotAcceptable); |
| | 0 | 609 | | return; |
| | | 610 | | } |
| | | 611 | | |
| | 0 | 612 | | if (Logger.IsEnabled(LogEventLevel.Verbose)) |
| | | 613 | | { |
| | 0 | 614 | | Logger.Verbose( |
| | 0 | 615 | | "Selected response media type for status code: {StatusCode}, MediaType={MediaType}, Accept={Accept}", |
| | 0 | 616 | | statusCode, |
| | 0 | 617 | | mediaType, |
| | 0 | 618 | | acceptHeader); |
| | | 619 | | } |
| | | 620 | | |
| | 0 | 621 | | await WriteByMediaTypeAsync(mediaType.ContentType, inputObject, statusCode); |
| | 3 | 622 | | } |
| | | 623 | | |
| | | 624 | | /// <summary> |
| | | 625 | | /// Determines whether OpenAPI response content-type enforcement should run for the current route. |
| | | 626 | | /// </summary> |
| | | 627 | | /// <remarks> |
| | | 628 | | /// Enforcement is only enabled for routes that carry OpenAPI descriptive metadata. |
| | | 629 | | /// Non-OpenAPI routes continue using legacy Accept-based negotiation. |
| | | 630 | | /// </remarks> |
| | | 631 | | /// <returns>True when the route has OpenAPI metadata; otherwise false.</returns> |
| | 11 | 632 | | private bool ShouldEnforceOpenApiResponseContentTypes() => MapRouteOptions.IsOpenApiAnnotatedFunctionRoute; |
| | | 633 | | |
| | | 634 | | /// <summary> |
| | | 635 | | /// Queues a response payload for deferred writing, applying configured response schema conversion and validation wh |
| | | 636 | | /// </summary> |
| | | 637 | | /// <param name="inputObject">The payload to queue.</param> |
| | | 638 | | /// <param name="statusCode">The HTTP status code associated with the payload.</param> |
| | | 639 | | public void QueueResponseForWrite(object? inputObject, int statusCode = StatusCodes.Status200OK) |
| | | 640 | | { |
| | 5 | 641 | | if (inputObject is null) |
| | | 642 | | { |
| | 1 | 643 | | PostPonedWriteObject = new WriteObject(null, statusCode, StatusCodes.Status500InternalServerError); |
| | 1 | 644 | | return; |
| | | 645 | | } |
| | | 646 | | |
| | | 647 | | try |
| | | 648 | | { |
| | 4 | 649 | | if (!TryGetResponseSchemaTypeForStatus(statusCode, out var schemaType, out var schemaTypeName)) |
| | | 650 | | { |
| | 1 | 651 | | PostPonedWriteObject = new WriteObject(inputObject, statusCode); |
| | 1 | 652 | | return; |
| | | 653 | | } |
| | | 654 | | |
| | 3 | 655 | | if (schemaType is null) |
| | | 656 | | { |
| | 1 | 657 | | Logger.Error("Unable to resolve response schema type '{SchemaTypeName}' for status code {StatusCode}.", |
| | 1 | 658 | | PostPonedWriteObject = new WriteObject(null, statusCode, StatusCodes.Status500InternalServerError); |
| | 1 | 659 | | return; |
| | | 660 | | } |
| | | 661 | | |
| | 2 | 662 | | var inputType = inputObject.GetType(); |
| | 2 | 663 | | var valueToWrite = schemaType.IsInstanceOfType(inputObject) || inputType == schemaType |
| | 2 | 664 | | ? inputObject |
| | 2 | 665 | | : ConvertSchemaValue(inputObject, schemaType); |
| | | 666 | | |
| | 2 | 667 | | if (!ValidateRequiredProperties(valueToWrite, out var missingProperties)) |
| | | 668 | | { |
| | 1 | 669 | | Logger.WarningSanitized( |
| | 1 | 670 | | "Response object failed required-property validation for schema type {SchemaTypeName}. Missing: {Mis |
| | 1 | 671 | | schemaType.FullName, |
| | 1 | 672 | | string.IsNullOrEmpty(missingProperties) ? "unknown required properties" : missingProperties); |
| | | 673 | | |
| | 1 | 674 | | PostPonedWriteObject = new WriteObject(null, statusCode, StatusCodes.Status500InternalServerError); |
| | 1 | 675 | | return; |
| | | 676 | | } |
| | | 677 | | |
| | 1 | 678 | | PostPonedWriteObject = new WriteObject(valueToWrite, statusCode); |
| | 1 | 679 | | } |
| | 0 | 680 | | catch (Exception ex) |
| | | 681 | | { |
| | 0 | 682 | | Logger.Error(ex, "Failed to convert response object for status code {StatusCode}.", statusCode); |
| | 0 | 683 | | PostPonedWriteObject = new WriteObject(null, statusCode, StatusCodes.Status500InternalServerError); |
| | 0 | 684 | | } |
| | 4 | 685 | | } |
| | | 686 | | |
| | | 687 | | /// <summary> |
| | | 688 | | /// Selects the most appropriate response media type based on the Accept header. |
| | | 689 | | /// </summary> |
| | | 690 | | /// <param name="acceptHeader">The value of the Accept header from the request.</param> |
| | | 691 | | /// <param name="supported">A list of supported media types to match against the Accept header.</param> |
| | | 692 | | /// <param name="defaultType">The default media type to use if no match is found. Defaults to "text/plain".</param> |
| | | 693 | | /// <returns>The selected media type as a string.</returns> |
| | | 694 | | /// <remarks> |
| | | 695 | | /// This method parses the Accept header, orders the media types by quality factor, |
| | | 696 | | /// and selects the first supported media type. If none are supported returns null |
| | | 697 | | /// </remarks> |
| | | 698 | | private static ContentTypeWithSchema? SelectResponseMediaType(string? acceptHeader, IReadOnlyList<ContentTypeWithSch |
| | | 699 | | { |
| | 8 | 700 | | if (supported.Count == 0) |
| | | 701 | | { |
| | 0 | 702 | | return new ContentTypeWithSchema(defaultType, null); |
| | | 703 | | } |
| | | 704 | | |
| | 8 | 705 | | if (string.IsNullOrWhiteSpace(acceptHeader)) |
| | | 706 | | { |
| | 0 | 707 | | return supported[0]; |
| | | 708 | | } |
| | | 709 | | |
| | 8 | 710 | | if (!MediaTypeHeaderValue.TryParseList([acceptHeader], out var accepts) || accepts.Count == 0) |
| | | 711 | | { |
| | 0 | 712 | | return supported[0]; |
| | | 713 | | } |
| | | 714 | | |
| | 16 | 715 | | var supportsAnyMediaType = supported.Any(s => string.Equals(MediaTypeHelper.Normalize(s.ContentType), "*/*", Str |
| | | 716 | | |
| | 8 | 717 | | var supportedNormalized = new string[supported.Count]; |
| | 8 | 718 | | var supportedCanonical = new string[supported.Count]; |
| | 32 | 719 | | for (var i = 0; i < supported.Count; i++) |
| | | 720 | | { |
| | 8 | 721 | | supportedNormalized[i] = MediaTypeHelper.Normalize(supported[i].ContentType); |
| | 8 | 722 | | supportedCanonical[i] = MediaTypeHelper.Canonicalize(supported[i].ContentType); |
| | | 723 | | } |
| | | 724 | | |
| | 33 | 725 | | foreach (var a in accepts.OrderByDescending(x => x.Quality ?? 1.0)) |
| | | 726 | | { |
| | 8 | 727 | | var accept = a.MediaType.Value; |
| | | 728 | | |
| | 8 | 729 | | if (accept is null) |
| | | 730 | | { |
| | | 731 | | continue; |
| | | 732 | | } |
| | | 733 | | |
| | | 734 | | // Normalize first so we can reliably detect wildcards and avoid treating them as canonical aliases. |
| | 8 | 735 | | var acceptNormalized = MediaTypeHelper.Normalize(accept); |
| | | 736 | | |
| | 8 | 737 | | if (supportsAnyMediaType) |
| | | 738 | | { |
| | 8 | 739 | | return SelectWhenAnyMediaTypeSupported(acceptNormalized, defaultType); |
| | | 740 | | } |
| | | 741 | | |
| | 0 | 742 | | var matched = SelectFromConfiguredSupportedMediaTypes(acceptNormalized, supported, supportedNormalized, supp |
| | 0 | 743 | | if (matched is not null) |
| | | 744 | | { |
| | 0 | 745 | | return matched; |
| | | 746 | | } |
| | | 747 | | } |
| | | 748 | | // No match found; return default |
| | 0 | 749 | | return null; |
| | 8 | 750 | | } |
| | | 751 | | |
| | | 752 | | /// <summary> |
| | | 753 | | /// Selects a response media type when the configured supported list includes <c>*/*</c>. |
| | | 754 | | /// </summary> |
| | | 755 | | /// <param name="acceptNormalized">The normalized Accept media type.</param> |
| | | 756 | | /// <param name="defaultType">The default media type fallback.</param> |
| | | 757 | | /// <returns>The selected media type entry.</returns> |
| | | 758 | | private static ContentTypeWithSchema SelectWhenAnyMediaTypeSupported(string acceptNormalized, string defaultType) |
| | | 759 | | { |
| | 8 | 760 | | if (string.Equals(acceptNormalized, "*/*", StringComparison.OrdinalIgnoreCase) || |
| | 8 | 761 | | acceptNormalized.EndsWith("/*", StringComparison.OrdinalIgnoreCase)) |
| | | 762 | | { |
| | 1 | 763 | | return new ContentTypeWithSchema(defaultType, null); |
| | | 764 | | } |
| | | 765 | | |
| | 7 | 766 | | var writerMediaType = ResolveWriterMediaType(acceptNormalized, defaultType); |
| | 7 | 767 | | return new ContentTypeWithSchema(writerMediaType, null); |
| | | 768 | | } |
| | | 769 | | |
| | | 770 | | /// <summary> |
| | | 771 | | /// Selects a response media type from explicitly configured supported media types. |
| | | 772 | | /// </summary> |
| | | 773 | | /// <param name="acceptNormalized">The normalized Accept media type.</param> |
| | | 774 | | /// <param name="supported">The configured supported media type entries.</param> |
| | | 775 | | /// <param name="supportedNormalized">Normalized supported media types in index-aligned order.</param> |
| | | 776 | | /// <param name="supportedCanonical">Canonical supported media types in index-aligned order.</param> |
| | | 777 | | /// <returns>The matched media type entry, or null when no match exists.</returns> |
| | | 778 | | private static ContentTypeWithSchema? SelectFromConfiguredSupportedMediaTypes( |
| | | 779 | | string acceptNormalized, |
| | | 780 | | IReadOnlyList<ContentTypeWithSchema> supported, |
| | | 781 | | IReadOnlyList<string> supportedNormalized, |
| | | 782 | | IReadOnlyList<string> supportedCanonical) |
| | | 783 | | { |
| | 0 | 784 | | if (string.Equals(acceptNormalized, "*/*", StringComparison.OrdinalIgnoreCase)) |
| | | 785 | | { |
| | 0 | 786 | | return supported[0]; |
| | | 787 | | } |
| | | 788 | | |
| | 0 | 789 | | if (acceptNormalized.EndsWith("/*", StringComparison.OrdinalIgnoreCase)) |
| | | 790 | | { |
| | 0 | 791 | | var prefix = acceptNormalized[..^1]; // "application/" |
| | 0 | 792 | | for (var i = 0; i < supported.Count; i++) |
| | | 793 | | { |
| | 0 | 794 | | if (supportedNormalized[i].StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) |
| | | 795 | | { |
| | 0 | 796 | | return supported[i]; |
| | | 797 | | } |
| | | 798 | | } |
| | | 799 | | |
| | 0 | 800 | | return null; |
| | | 801 | | } |
| | | 802 | | |
| | 0 | 803 | | var acceptCanonical = MediaTypeHelper.Canonicalize(acceptNormalized); |
| | | 804 | | |
| | 0 | 805 | | for (var i = 0; i < supported.Count; i++) |
| | | 806 | | { |
| | 0 | 807 | | if (string.Equals(supportedNormalized[i], acceptNormalized, StringComparison.OrdinalIgnoreCase)) |
| | | 808 | | { |
| | 0 | 809 | | return supported[i]; |
| | | 810 | | } |
| | | 811 | | } |
| | | 812 | | |
| | 0 | 813 | | for (var i = 0; i < supported.Count; i++) |
| | | 814 | | { |
| | 0 | 815 | | if (string.Equals(supportedCanonical[i], acceptCanonical, StringComparison.OrdinalIgnoreCase)) |
| | | 816 | | { |
| | 0 | 817 | | return supported[i]; |
| | | 818 | | } |
| | | 819 | | } |
| | | 820 | | |
| | 0 | 821 | | return null; |
| | | 822 | | } |
| | | 823 | | |
| | | 824 | | /// <summary> |
| | | 825 | | /// Resolves an incoming Accept media type to a concrete response writer media type. |
| | | 826 | | /// </summary> |
| | | 827 | | /// <param name="acceptNormalized">The normalized Accept media type.</param> |
| | | 828 | | /// <param name="defaultType">The fallback media type.</param> |
| | | 829 | | /// <returns>A concrete media type supported by response writers.</returns> |
| | | 830 | | private static string ResolveWriterMediaType(string acceptNormalized, string defaultType) |
| | | 831 | | { |
| | 7 | 832 | | var canonical = MediaTypeHelper.Canonicalize(acceptNormalized); |
| | | 833 | | // For common structured types with well-known suffixes, return the canonical type to ensure we return a support |
| | 7 | 834 | | if (string.Equals(canonical, "application/json", StringComparison.OrdinalIgnoreCase) || |
| | 7 | 835 | | string.Equals(canonical, "application/xml", StringComparison.OrdinalIgnoreCase) || |
| | 7 | 836 | | string.Equals(canonical, "application/yaml", StringComparison.OrdinalIgnoreCase)) |
| | | 837 | | { |
| | 6 | 838 | | return canonical; |
| | | 839 | | } |
| | | 840 | | // Allow text/csv and application/x-www-form-urlencoded as they are commonly used text-based formats that suppor |
| | 1 | 841 | | if (string.Equals(acceptNormalized, "text/csv", StringComparison.OrdinalIgnoreCase) || |
| | 1 | 842 | | string.Equals(acceptNormalized, "application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) |
| | | 843 | | { |
| | 1 | 844 | | return acceptNormalized; |
| | | 845 | | } |
| | | 846 | | // For other text/* types, default to text/plain since we don't want to accidentally return HTML or similar type |
| | 0 | 847 | | if (acceptNormalized.StartsWith("text/", StringComparison.OrdinalIgnoreCase)) |
| | | 848 | | { |
| | 0 | 849 | | return "text/plain"; |
| | | 850 | | } |
| | | 851 | | // For other types, we would need explicit support configured to return them; default to the provided default ty |
| | 0 | 852 | | return defaultType; |
| | | 853 | | } |
| | | 854 | | |
| | | 855 | | /// <summary> |
| | | 856 | | /// Resolves response content types for a status code using exact, range (e.g., 4XX), then default. |
| | | 857 | | /// </summary> |
| | | 858 | | /// <param name="contentTypes">The content type map keyed by status code, range, or default.</param> |
| | | 859 | | /// <param name="statusCode">The HTTP status code to resolve.</param> |
| | | 860 | | /// <param name="values">The resolved content types, if found.</param> |
| | | 861 | | /// <returns>True when a matching entry is found, including explicit empty mappings.</returns> |
| | | 862 | | private static bool TryGetResponseContentTypes( |
| | | 863 | | IDictionary<string, ICollection<ContentTypeWithSchema>>? contentTypes, |
| | | 864 | | int statusCode, |
| | | 865 | | out ICollection<ContentTypeWithSchema>? values) |
| | | 866 | | { |
| | 7 | 867 | | values = null; |
| | 7 | 868 | | if (contentTypes is null || contentTypes.Count == 0) |
| | | 869 | | { |
| | 1 | 870 | | return false; |
| | | 871 | | } |
| | | 872 | | |
| | 6 | 873 | | var statusKey = statusCode.ToString(CultureInfo.InvariantCulture); |
| | 6 | 874 | | if (TryGetValueIgnoreCase(contentTypes, statusKey, out values)) |
| | | 875 | | { |
| | 4 | 876 | | return true; |
| | | 877 | | } |
| | | 878 | | |
| | 2 | 879 | | if (statusCode is >= 100 and <= 599) |
| | | 880 | | { |
| | | 881 | | // Allow OpenAPI-style wildcard keys such as: |
| | | 882 | | // - 4XX (all 4xx) |
| | | 883 | | // These are matched case-insensitively. |
| | 2 | 884 | | var rangeKey = $"{statusCode / 100}XX"; |
| | 2 | 885 | | if (TryGetValueIgnoreCase(contentTypes, rangeKey, out values)) |
| | | 886 | | { |
| | 1 | 887 | | return true; |
| | | 888 | | } |
| | | 889 | | } |
| | | 890 | | |
| | 1 | 891 | | if (TryGetValueIgnoreCase(contentTypes, "default", out values)) |
| | | 892 | | { |
| | 1 | 893 | | return true; |
| | | 894 | | } |
| | | 895 | | |
| | 0 | 896 | | values = null; |
| | 0 | 897 | | return false; |
| | | 898 | | } |
| | | 899 | | |
| | | 900 | | /// <summary> |
| | | 901 | | /// Attempts to resolve a configured response schema type for the given status code. |
| | | 902 | | /// </summary> |
| | | 903 | | /// <param name="statusCode">The status code for which a schema should be resolved.</param> |
| | | 904 | | /// <param name="schemaType">The resolved schema type, when available.</param> |
| | | 905 | | /// <param name="schemaTypeName">The configured schema type name.</param> |
| | | 906 | | /// <returns>True when a schema mapping exists for the status code and includes schema metadata.</returns> |
| | | 907 | | private bool TryGetResponseSchemaTypeForStatus(int statusCode, out Type? schemaType, out string? schemaTypeName) |
| | | 908 | | { |
| | 4 | 909 | | schemaType = null; |
| | 4 | 910 | | schemaTypeName = null; |
| | | 911 | | |
| | 4 | 912 | | if (!TryGetResponseContentTypes(MapRouteOptions.DefaultResponseContentType, statusCode, out var mappings) || map |
| | | 913 | | { |
| | 0 | 914 | | return false; |
| | | 915 | | } |
| | | 916 | | |
| | 4 | 917 | | var first = mappings.FirstOrDefault(); |
| | 4 | 918 | | if (first is null || string.IsNullOrWhiteSpace(first.Schema)) |
| | | 919 | | { |
| | 1 | 920 | | return false; |
| | | 921 | | } |
| | | 922 | | |
| | 3 | 923 | | schemaTypeName = first.Schema; |
| | 3 | 924 | | schemaType = ResolveSchemaType(schemaTypeName); |
| | 3 | 925 | | return true; |
| | | 926 | | } |
| | | 927 | | |
| | | 928 | | /// <summary> |
| | | 929 | | /// Resolves a type by full name, short name, or assembly-qualified name from loaded assemblies. |
| | | 930 | | /// </summary> |
| | | 931 | | /// <param name="schemaTypeName">The schema type name to resolve.</param> |
| | | 932 | | /// <returns>The resolved type when found; otherwise null.</returns> |
| | | 933 | | private static Type? ResolveSchemaType(string schemaTypeName) |
| | | 934 | | { |
| | 3 | 935 | | if (string.IsNullOrWhiteSpace(schemaTypeName)) |
| | | 936 | | { |
| | 0 | 937 | | return null; |
| | | 938 | | } |
| | | 939 | | |
| | 3 | 940 | | var candidates = new List<Type>(); |
| | | 941 | | |
| | 3 | 942 | | var directType = Type.GetType(schemaTypeName, throwOnError: false, ignoreCase: true); |
| | 3 | 943 | | if (directType is not null) |
| | | 944 | | { |
| | 0 | 945 | | candidates.Add(directType); |
| | | 946 | | } |
| | | 947 | | |
| | 1274 | 948 | | foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) |
| | | 949 | | { |
| | 634 | 950 | | CollectSchemaTypeCandidatesFromAssembly(assembly, schemaTypeName, candidates); |
| | | 951 | | } |
| | | 952 | | |
| | 3 | 953 | | return SelectPreferredSchemaType(candidates); |
| | | 954 | | } |
| | | 955 | | |
| | | 956 | | /// <summary> |
| | | 957 | | /// Collects schema type candidates from an assembly by direct and name-based matching. |
| | | 958 | | /// </summary> |
| | | 959 | | /// <param name="assembly">The assembly to scan.</param> |
| | | 960 | | /// <param name="schemaTypeName">The schema type name to resolve.</param> |
| | | 961 | | /// <param name="candidates">The destination list of matching candidates.</param> |
| | | 962 | | private static void CollectSchemaTypeCandidatesFromAssembly(Assembly assembly, string schemaTypeName, List<Type> can |
| | | 963 | | { |
| | 634 | 964 | | var assemblyType = assembly.GetType(schemaTypeName, throwOnError: false, ignoreCase: true); |
| | 634 | 965 | | if (assemblyType is not null) |
| | | 966 | | { |
| | 2 | 967 | | candidates.Add(assemblyType); |
| | | 968 | | } |
| | | 969 | | |
| | | 970 | | Type[] typeCandidates; |
| | | 971 | | try |
| | | 972 | | { |
| | 634 | 973 | | typeCandidates = assembly.GetTypes(); |
| | 634 | 974 | | } |
| | 0 | 975 | | catch (ReflectionTypeLoadException ex) |
| | | 976 | | { |
| | 0 | 977 | | typeCandidates = [.. ex.Types.Where(t => t is not null)!]; |
| | 0 | 978 | | } |
| | 0 | 979 | | catch |
| | | 980 | | { |
| | 0 | 981 | | return; |
| | | 982 | | } |
| | | 983 | | |
| | 232618 | 984 | | foreach (var typeCandidate in typeCandidates) |
| | | 985 | | { |
| | 115675 | 986 | | if (typeCandidate is not null && IsMatchingSchemaTypeName(typeCandidate, schemaTypeName)) |
| | | 987 | | { |
| | 2 | 988 | | candidates.Add(typeCandidate); |
| | | 989 | | } |
| | | 990 | | } |
| | 634 | 991 | | } |
| | | 992 | | |
| | | 993 | | /// <summary> |
| | | 994 | | /// Determines whether a candidate type matches the provided schema type name. |
| | | 995 | | /// </summary> |
| | | 996 | | /// <param name="typeCandidate">The type candidate to evaluate.</param> |
| | | 997 | | /// <param name="schemaTypeName">The schema type name to match.</param> |
| | | 998 | | /// <returns>True when the candidate matches by full name, short name, or assembly-qualified prefix.</returns> |
| | | 999 | | private static bool IsMatchingSchemaTypeName(Type typeCandidate, string schemaTypeName) |
| | 115675 | 1000 | | => string.Equals(typeCandidate.FullName, schemaTypeName, StringComparison.OrdinalIgnoreCase) |
| | 115675 | 1001 | | || string.Equals(typeCandidate.Name, schemaTypeName, StringComparison.OrdinalIgnoreCase) |
| | 115675 | 1002 | | || (!string.IsNullOrWhiteSpace(typeCandidate.AssemblyQualifiedName) |
| | 115675 | 1003 | | && typeCandidate.AssemblyQualifiedName.StartsWith(schemaTypeName + ",", StringComparison.OrdinalIgnoreCas |
| | | 1004 | | |
| | | 1005 | | /// <summary> |
| | | 1006 | | /// Selects the preferred schema type from collected candidates. |
| | | 1007 | | /// </summary> |
| | | 1008 | | /// <param name="candidates">The collected type candidates.</param> |
| | | 1009 | | /// <returns>The preferred schema type, or null when no candidate exists.</returns> |
| | | 1010 | | private static Type? SelectPreferredSchemaType(IReadOnlyList<Type> candidates) |
| | | 1011 | | { |
| | 3 | 1012 | | var distinct = candidates |
| | 4 | 1013 | | .Where(t => t is not null) |
| | 4 | 1014 | | .GroupBy(t => string.IsNullOrWhiteSpace(t.AssemblyQualifiedName) ? t.FullName : t.AssemblyQualifiedName, Str |
| | 2 | 1015 | | .Select(g => g.First()) |
| | 3 | 1016 | | .ToList(); |
| | | 1017 | | |
| | 3 | 1018 | | if (distinct.Count == 0) |
| | | 1019 | | { |
| | 1 | 1020 | | return null; |
| | | 1021 | | } |
| | | 1022 | | |
| | 2 | 1023 | | var generatedCandidate = distinct.FirstOrDefault(t => |
| | 4 | 1024 | | t.GetProperty("XmlMetadata", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy) is n |
| | | 1025 | | |
| | 2 | 1026 | | return generatedCandidate ?? distinct[0]; |
| | | 1027 | | } |
| | | 1028 | | |
| | | 1029 | | /// <summary> |
| | | 1030 | | /// Converts a value to the target schema type. |
| | | 1031 | | /// </summary> |
| | | 1032 | | /// <param name="value">The source value.</param> |
| | | 1033 | | /// <param name="targetType">The destination type.</param> |
| | | 1034 | | /// <returns>The converted value.</returns> |
| | | 1035 | | private static object? ConvertSchemaValue(object? value, Type targetType) |
| | | 1036 | | { |
| | 5 | 1037 | | value = UnwrapPowerShellValue(value); |
| | 5 | 1038 | | if (value is null) |
| | | 1039 | | { |
| | 0 | 1040 | | return null; |
| | | 1041 | | } |
| | | 1042 | | // If the value is already assignable to the target type, return it directly without further conversion. |
| | 5 | 1043 | | var valueType = value.GetType(); |
| | 5 | 1044 | | if (targetType.IsInstanceOfType(value) || valueType == targetType) |
| | | 1045 | | { |
| | 3 | 1046 | | return value; |
| | | 1047 | | } |
| | | 1048 | | // Handle nullable types by converting to the underlying type. |
| | 2 | 1049 | | var nullableUnderlying = Nullable.GetUnderlyingType(targetType); |
| | 2 | 1050 | | if (nullableUnderlying is not null) |
| | | 1051 | | { |
| | 0 | 1052 | | return ConvertSchemaValue(value, nullableUnderlying); |
| | | 1053 | | } |
| | | 1054 | | // If the target type is a map-like type (e.g., IDictionary) and the value is an IDictionary, return it directly |
| | 2 | 1055 | | if (IsMapLikeType(targetType) && value is IDictionary) |
| | | 1056 | | { |
| | 0 | 1057 | | return value; |
| | | 1058 | | } |
| | | 1059 | | // If the target type is an array, attempt to convert the value to an array of the target element type. This han |
| | 2 | 1060 | | if (targetType.IsArray) |
| | | 1061 | | { |
| | 0 | 1062 | | return ConvertSchemaArrayValue(value, targetType); |
| | | 1063 | | } |
| | | 1064 | | // Attempt dictionary-to-type conversion for schema values, which allows for flexible object construction from d |
| | 2 | 1065 | | if (TryConvertSchemaDictionaryValue(value, targetType, out var dictionaryConvertedValue)) |
| | | 1066 | | { |
| | 2 | 1067 | | return dictionaryConvertedValue; |
| | | 1068 | | } |
| | | 1069 | | // Attempt PowerShell object conversion, which allows for flexible handling of PowerShell-specific objects and t |
| | 0 | 1070 | | if (TryConvertPowerShellObjectToType(value, targetType, out var convertedPowerShellObject)) |
| | | 1071 | | { |
| | 0 | 1072 | | return convertedPowerShellObject; |
| | | 1073 | | } |
| | | 1074 | | // Attempt single-argument constructor conversion as a last resort before simple conversions, as it may be more |
| | 0 | 1075 | | if (TryConvertViaSingleArgumentConstructor(value, targetType, out var constructorConvertedValue)) |
| | | 1076 | | { |
| | 0 | 1077 | | return constructorConvertedValue; |
| | | 1078 | | } |
| | | 1079 | | // As a final fallback, attempt simple conversions for primitive types and common convertible types, which allow |
| | 0 | 1080 | | return TryConvertSimple(value, targetType, out var convertedValue) ? convertedValue : value; |
| | | 1081 | | } |
| | | 1082 | | |
| | | 1083 | | /// <summary> |
| | | 1084 | | /// Converts a schema value to an array of the requested target type. |
| | | 1085 | | /// </summary> |
| | | 1086 | | /// <param name="value">The source value to convert.</param> |
| | | 1087 | | /// <param name="targetArrayType">The destination array type.</param> |
| | | 1088 | | /// <returns>A typed array instance populated from the source value.</returns> |
| | | 1089 | | private static object ConvertSchemaArrayValue(object value, Type targetArrayType) |
| | | 1090 | | { |
| | 0 | 1091 | | var elementType = targetArrayType.GetElementType() ?? typeof(object); |
| | 0 | 1092 | | if (value is IEnumerable enumerable and not string) |
| | | 1093 | | { |
| | 0 | 1094 | | return ConvertEnumerableToTypedArray(enumerable, elementType); |
| | | 1095 | | } |
| | | 1096 | | // If the value is not an enumerable, attempt to convert it as a single element array. |
| | 0 | 1097 | | return ConvertSingleValueToTypedArray(value, elementType); |
| | | 1098 | | } |
| | | 1099 | | |
| | | 1100 | | /// <summary> |
| | | 1101 | | /// Converts an enumerable source to a typed destination array. |
| | | 1102 | | /// </summary> |
| | | 1103 | | /// <param name="enumerable">The source enumerable values.</param> |
| | | 1104 | | /// <param name="elementType">The destination element type.</param> |
| | | 1105 | | /// <returns>A typed array containing converted elements.</returns> |
| | | 1106 | | private static Array ConvertEnumerableToTypedArray(IEnumerable enumerable, Type elementType) |
| | | 1107 | | { |
| | 0 | 1108 | | var materialized = new List<object?>(); |
| | 0 | 1109 | | foreach (var item in enumerable) |
| | | 1110 | | { |
| | 0 | 1111 | | materialized.Add(ConvertSchemaValue(item, elementType)); |
| | | 1112 | | } |
| | | 1113 | | // Create a typed array of the destination element type and populate it with the converted values, ensuring that |
| | 0 | 1114 | | var typedArray = Array.CreateInstance(elementType, materialized.Count); |
| | 0 | 1115 | | for (var i = 0; i < materialized.Count; i++) |
| | | 1116 | | { |
| | 0 | 1117 | | var itemToAssign = EnsureArrayElementAssignable(materialized[i], elementType, allowSimpleFallback: false); |
| | 0 | 1118 | | typedArray.SetValue(itemToAssign, i); |
| | | 1119 | | } |
| | | 1120 | | // Return the fully converted and typed array to be used as the response value, which ensures that the response |
| | 0 | 1121 | | return typedArray; |
| | | 1122 | | } |
| | | 1123 | | |
| | | 1124 | | /// <summary> |
| | | 1125 | | /// Converts a single source value to a one-element typed destination array. |
| | | 1126 | | /// </summary> |
| | | 1127 | | /// <param name="value">The source value.</param> |
| | | 1128 | | /// <param name="elementType">The destination element type.</param> |
| | | 1129 | | /// <returns>A one-element typed array containing the converted value.</returns> |
| | | 1130 | | private static Array ConvertSingleValueToTypedArray(object value, Type elementType) |
| | | 1131 | | { |
| | 0 | 1132 | | var singleItemArray = Array.CreateInstance(elementType, 1); |
| | 0 | 1133 | | var singleElement = EnsureArrayElementAssignable(ConvertSchemaValue(value, elementType), elementType, allowSimpl |
| | 0 | 1134 | | singleItemArray.SetValue(singleElement, 0); |
| | 0 | 1135 | | return singleItemArray; |
| | | 1136 | | } |
| | | 1137 | | |
| | | 1138 | | /// <summary> |
| | | 1139 | | /// Ensures that an array element is assignable to the destination element type. |
| | | 1140 | | /// </summary> |
| | | 1141 | | /// <param name="candidate">The candidate value to assign.</param> |
| | | 1142 | | /// <param name="elementType">The required destination element type.</param> |
| | | 1143 | | /// <param name="allowSimpleFallback">Whether to attempt simple conversion before throwing.</param> |
| | | 1144 | | /// <returns>A value assignable to the destination element type, or null.</returns> |
| | | 1145 | | /// <exception cref="InvalidCastException">Thrown when conversion to the destination element type fails.</exception> |
| | | 1146 | | private static object? EnsureArrayElementAssignable(object? candidate, Type elementType, bool allowSimpleFallback) |
| | | 1147 | | { |
| | 0 | 1148 | | var unwrapped = UnwrapPowerShellValue(candidate); |
| | 0 | 1149 | | if (unwrapped is null || elementType.IsInstanceOfType(unwrapped)) |
| | | 1150 | | { |
| | 0 | 1151 | | return unwrapped; |
| | | 1152 | | } |
| | | 1153 | | |
| | | 1154 | | // Attempt schema conversion on the element to ensure it is compatible with the destination element type, which |
| | 0 | 1155 | | var convertedElement = UnwrapPowerShellValue(ConvertSchemaValue(unwrapped, elementType)); |
| | 0 | 1156 | | if (convertedElement is null || elementType.IsInstanceOfType(convertedElement)) |
| | | 1157 | | { |
| | 0 | 1158 | | return convertedElement; |
| | | 1159 | | } |
| | | 1160 | | |
| | | 1161 | | // If allowed, attempt a simple conversion as a final fallback before throwing, which provides some leniency for |
| | 0 | 1162 | | if (allowSimpleFallback && |
| | 0 | 1163 | | TryConvertSimple(convertedElement, elementType, out var simpleConverted) && |
| | 0 | 1164 | | (simpleConverted is null || elementType.IsInstanceOfType(simpleConverted))) |
| | | 1165 | | { |
| | 0 | 1166 | | return simpleConverted; |
| | | 1167 | | } |
| | | 1168 | | |
| | | 1169 | | // If the element cannot be converted to the required type, throw an exception to indicate a schema validation f |
| | 0 | 1170 | | throw new InvalidCastException($"Object of type '{convertedElement.GetType().FullName}' cannot be converted to ' |
| | | 1171 | | } |
| | | 1172 | | |
| | | 1173 | | /// <summary> |
| | | 1174 | | /// Attempts dictionary-to-type conversion for schema values. |
| | | 1175 | | /// </summary> |
| | | 1176 | | /// <param name="value">The source value.</param> |
| | | 1177 | | /// <param name="targetType">The destination type.</param> |
| | | 1178 | | /// <param name="convertedValue">The converted value when successful.</param> |
| | | 1179 | | /// <returns>True when dictionary conversion succeeds; otherwise false.</returns> |
| | | 1180 | | private static bool TryConvertSchemaDictionaryValue(object value, Type targetType, out object? convertedValue) |
| | | 1181 | | { |
| | 2 | 1182 | | convertedValue = null; |
| | 2 | 1183 | | if (value is not IDictionary dictionary) |
| | | 1184 | | { |
| | 0 | 1185 | | return false; |
| | | 1186 | | } |
| | | 1187 | | |
| | 2 | 1188 | | var (success, convertedDictionaryValue) = TryConvertDictionaryToType(dictionary, targetType); |
| | 2 | 1189 | | if (!success) |
| | | 1190 | | { |
| | 0 | 1191 | | return false; |
| | | 1192 | | } |
| | | 1193 | | |
| | 2 | 1194 | | convertedValue = convertedDictionaryValue; |
| | 2 | 1195 | | return true; |
| | | 1196 | | } |
| | | 1197 | | |
| | | 1198 | | /// <summary> |
| | | 1199 | | /// Attempts to convert a value to the target type by using single-argument constructors. |
| | | 1200 | | /// </summary> |
| | | 1201 | | /// <param name="value">The source value.</param> |
| | | 1202 | | /// <param name="targetType">The destination type.</param> |
| | | 1203 | | /// <param name="convertedValue">The constructed value when successful.</param> |
| | | 1204 | | /// <returns>True when a single-argument constructor conversion succeeds; otherwise false.</returns> |
| | | 1205 | | private static bool TryConvertViaSingleArgumentConstructor(object value, Type targetType, out object? convertedValue |
| | | 1206 | | { |
| | 0 | 1207 | | convertedValue = null; |
| | 0 | 1208 | | foreach (var constructor in targetType.GetConstructors().Where(c => c.GetParameters().Length == 1)) |
| | | 1209 | | { |
| | 0 | 1210 | | var parameterType = constructor.GetParameters()[0].ParameterType; |
| | 0 | 1211 | | if (!TryConvertSimple(value, parameterType, out var convertedArg)) |
| | | 1212 | | { |
| | | 1213 | | continue; |
| | | 1214 | | } |
| | | 1215 | | |
| | 0 | 1216 | | convertedValue = constructor.Invoke([convertedArg]); |
| | 0 | 1217 | | return true; |
| | | 1218 | | } |
| | | 1219 | | |
| | 0 | 1220 | | return false; |
| | 0 | 1221 | | } |
| | | 1222 | | |
| | | 1223 | | /// <summary> |
| | | 1224 | | /// Unwraps common PowerShell wrapper/sentinel values into .NET runtime values. |
| | | 1225 | | /// </summary> |
| | | 1226 | | /// <param name="value">The value to unwrap.</param> |
| | | 1227 | | /// <returns>The unwrapped value, or null for AutomationNull.</returns> |
| | | 1228 | | private static object? UnwrapPowerShellValue(object? value) |
| | | 1229 | | { |
| | 5 | 1230 | | if (value is null) |
| | | 1231 | | { |
| | 0 | 1232 | | return null; |
| | | 1233 | | } |
| | | 1234 | | |
| | 5 | 1235 | | if (IsPowerShellAutomationNull(value)) |
| | | 1236 | | { |
| | 0 | 1237 | | return null; |
| | | 1238 | | } |
| | | 1239 | | |
| | 5 | 1240 | | if (value is PSObject psObject) |
| | | 1241 | | { |
| | 0 | 1242 | | var baseObject = psObject.BaseObject; |
| | 0 | 1243 | | return baseObject is null || IsPowerShellAutomationNull(baseObject) |
| | 0 | 1244 | | ? null |
| | 0 | 1245 | | : baseObject; |
| | | 1246 | | } |
| | | 1247 | | |
| | 5 | 1248 | | return value; |
| | | 1249 | | } |
| | | 1250 | | |
| | | 1251 | | /// <summary> |
| | | 1252 | | /// Determines whether a value represents PowerShell's AutomationNull sentinel. |
| | | 1253 | | /// </summary> |
| | | 1254 | | /// <param name="value">The value to inspect.</param> |
| | | 1255 | | /// <returns>True when the value is PowerShell AutomationNull.</returns> |
| | | 1256 | | private static bool IsPowerShellAutomationNull(object value) |
| | | 1257 | | { |
| | 5 | 1258 | | var type = value.GetType(); |
| | 5 | 1259 | | return type.FullName?.Equals("System.Management.Automation.Internal.AutomationNull", StringComparison.Ordinal) = |
| | | 1260 | | } |
| | | 1261 | | |
| | | 1262 | | /// <summary> |
| | | 1263 | | /// Attempts to convert dictionary values to a strongly typed object. |
| | | 1264 | | /// </summary> |
| | | 1265 | | /// <param name="dictionary">The source dictionary.</param> |
| | | 1266 | | /// <param name="targetType">The destination type.</param> |
| | | 1267 | | /// <returns>A tuple indicating conversion success and converted value.</returns> |
| | | 1268 | | private static (bool Success, object? Value) TryConvertDictionaryToType(IDictionary dictionary, Type targetType) |
| | | 1269 | | { |
| | 2 | 1270 | | var defaultConstructor = targetType.GetConstructor(Type.EmptyTypes); |
| | 2 | 1271 | | if (defaultConstructor is null) |
| | | 1272 | | { |
| | 0 | 1273 | | return (false, null); |
| | | 1274 | | } |
| | | 1275 | | |
| | 2 | 1276 | | var instance = defaultConstructor.Invoke([]); |
| | 2 | 1277 | | var writableProperties = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance) |
| | 3 | 1278 | | .Where(p => p.CanWrite) |
| | 2 | 1279 | | .ToList(); |
| | | 1280 | | |
| | 10 | 1281 | | foreach (var property in writableProperties) |
| | | 1282 | | { |
| | 3 | 1283 | | var matchKey = FindDictionaryKey(dictionary, property.Name); |
| | 3 | 1284 | | if (matchKey is null) |
| | | 1285 | | { |
| | | 1286 | | continue; |
| | | 1287 | | } |
| | | 1288 | | |
| | 3 | 1289 | | var rawValue = dictionary[matchKey]; |
| | 3 | 1290 | | if (rawValue is IDictionary && IsMapLikeType(property.PropertyType)) |
| | | 1291 | | { |
| | 0 | 1292 | | return (true, dictionary); |
| | | 1293 | | } |
| | | 1294 | | |
| | 3 | 1295 | | var convertedPropertyValue = ConvertSchemaValue(rawValue, property.PropertyType); |
| | 3 | 1296 | | property.SetValue(instance, convertedPropertyValue); |
| | | 1297 | | } |
| | | 1298 | | |
| | 2 | 1299 | | return (true, instance); |
| | 0 | 1300 | | } |
| | | 1301 | | |
| | | 1302 | | /// <summary> |
| | | 1303 | | /// Attempts to convert a PowerShell custom object to a strongly typed object by mapping note properties. |
| | | 1304 | | /// </summary> |
| | | 1305 | | /// <param name="value">The source PowerShell object.</param> |
| | | 1306 | | /// <param name="targetType">The destination type.</param> |
| | | 1307 | | /// <param name="converted">The converted object when successful.</param> |
| | | 1308 | | /// <returns>True when conversion succeeds.</returns> |
| | | 1309 | | private static bool TryConvertPowerShellObjectToType(object value, Type targetType, out object? converted) |
| | | 1310 | | { |
| | 0 | 1311 | | converted = null; |
| | | 1312 | | |
| | 0 | 1313 | | var typeName = value.GetType().FullName; |
| | 0 | 1314 | | if (!string.Equals(typeName, "System.Management.Automation.PSCustomObject", StringComparison.Ordinal)) |
| | | 1315 | | { |
| | 0 | 1316 | | return false; |
| | | 1317 | | } |
| | | 1318 | | |
| | 0 | 1319 | | var asPsObject = value as PSObject ?? new PSObject(value); |
| | 0 | 1320 | | var dictionary = new Hashtable(StringComparer.OrdinalIgnoreCase); |
| | 0 | 1321 | | foreach (var property in asPsObject.Properties) |
| | | 1322 | | { |
| | 0 | 1323 | | if (property is null || string.IsNullOrWhiteSpace(property.Name)) |
| | | 1324 | | { |
| | | 1325 | | continue; |
| | | 1326 | | } |
| | | 1327 | | |
| | 0 | 1328 | | dictionary[property.Name] = property.Value; |
| | | 1329 | | } |
| | | 1330 | | |
| | 0 | 1331 | | var (success, convertedValue) = TryConvertDictionaryToType(dictionary, targetType); |
| | 0 | 1332 | | if (!success) |
| | | 1333 | | { |
| | 0 | 1334 | | return false; |
| | | 1335 | | } |
| | | 1336 | | |
| | 0 | 1337 | | converted = convertedValue; |
| | 0 | 1338 | | return true; |
| | | 1339 | | } |
| | | 1340 | | |
| | | 1341 | | /// <summary> |
| | | 1342 | | /// Finds a dictionary key by case-insensitive string comparison. |
| | | 1343 | | /// </summary> |
| | | 1344 | | /// <param name="dictionary">The dictionary to search.</param> |
| | | 1345 | | /// <param name="propertyName">The property name to match.</param> |
| | | 1346 | | /// <returns>The matching dictionary key, if found.</returns> |
| | | 1347 | | private static object? FindDictionaryKey(IDictionary dictionary, string propertyName) |
| | | 1348 | | { |
| | 11 | 1349 | | foreach (DictionaryEntry entry in dictionary) |
| | | 1350 | | { |
| | 4 | 1351 | | if (entry.Key is null) |
| | | 1352 | | { |
| | | 1353 | | continue; |
| | | 1354 | | } |
| | | 1355 | | |
| | 4 | 1356 | | var key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture); |
| | 4 | 1357 | | if (string.Equals(key, propertyName, StringComparison.OrdinalIgnoreCase)) |
| | | 1358 | | { |
| | 3 | 1359 | | return entry.Key; |
| | | 1360 | | } |
| | | 1361 | | } |
| | | 1362 | | |
| | 0 | 1363 | | return null; |
| | 3 | 1364 | | } |
| | | 1365 | | |
| | | 1366 | | /// <summary> |
| | | 1367 | | /// Validates required properties using generated helper methods when available. |
| | | 1368 | | /// </summary> |
| | | 1369 | | /// <param name="value">The converted value to validate.</param> |
| | | 1370 | | /// <param name="missingProperties">A comma-separated list of missing properties.</param> |
| | | 1371 | | /// <returns>True when validation succeeds or no validation helper exists.</returns> |
| | | 1372 | | private static bool ValidateRequiredProperties(object? value, out string missingProperties) |
| | | 1373 | | { |
| | 2 | 1374 | | missingProperties = string.Empty; |
| | 2 | 1375 | | if (value is null) |
| | | 1376 | | { |
| | 0 | 1377 | | return true; |
| | | 1378 | | } |
| | | 1379 | | |
| | 2 | 1380 | | var runtimeType = value.GetType(); |
| | 2 | 1381 | | var validateMethod = runtimeType.GetMethod("ValidateRequiredProperties", BindingFlags.Public | BindingFlags.Inst |
| | 2 | 1382 | | if (validateMethod is null) |
| | | 1383 | | { |
| | 1 | 1384 | | return true; |
| | | 1385 | | } |
| | | 1386 | | |
| | 1 | 1387 | | var validationResult = validateMethod.Invoke(value, null); |
| | 1 | 1388 | | if (validationResult is bool isValid && isValid) |
| | | 1389 | | { |
| | 0 | 1390 | | return true; |
| | | 1391 | | } |
| | | 1392 | | |
| | 1 | 1393 | | var missingMethod = runtimeType.GetMethod("GetMissingRequiredProperties", BindingFlags.Public | BindingFlags.Ins |
| | 1 | 1394 | | if (missingMethod is not null) |
| | | 1395 | | { |
| | 1 | 1396 | | var missing = missingMethod.Invoke(value, null); |
| | 1 | 1397 | | missingProperties = FormatMissingRequiredProperties(missing); |
| | | 1398 | | } |
| | | 1399 | | |
| | 1 | 1400 | | return false; |
| | | 1401 | | } |
| | | 1402 | | |
| | | 1403 | | /// <summary> |
| | | 1404 | | /// Formats missing required-property values returned by generated validation helpers. |
| | | 1405 | | /// </summary> |
| | | 1406 | | /// <param name="missing">The missing-properties payload returned by reflection invocation.</param> |
| | | 1407 | | /// <returns>A comma-separated string of missing property names, or an empty string when unavailable.</returns> |
| | | 1408 | | private static string FormatMissingRequiredProperties(object? missing) |
| | | 1409 | | { |
| | 1 | 1410 | | if (missing is IEnumerable<string> missingEnumerable) |
| | | 1411 | | { |
| | 1 | 1412 | | return string.Join(", ", missingEnumerable); |
| | | 1413 | | } |
| | | 1414 | | |
| | 0 | 1415 | | if (missing is IEnumerable genericEnumerable) |
| | | 1416 | | { |
| | 0 | 1417 | | var values = new List<string>(); |
| | 0 | 1418 | | foreach (var item in genericEnumerable) |
| | | 1419 | | { |
| | 0 | 1420 | | values.Add(item?.ToString() ?? string.Empty); |
| | | 1421 | | } |
| | | 1422 | | |
| | 0 | 1423 | | return string.Join(", ", values.Where(v => !string.IsNullOrWhiteSpace(v))); |
| | | 1424 | | } |
| | | 1425 | | |
| | 0 | 1426 | | return string.Empty; |
| | | 1427 | | } |
| | | 1428 | | |
| | | 1429 | | /// <summary> |
| | | 1430 | | /// Determines whether a type should be treated as map-like for dictionary passthrough. |
| | | 1431 | | /// </summary> |
| | | 1432 | | /// <param name="type">The type to inspect.</param> |
| | | 1433 | | /// <returns>True when the type is map-like.</returns> |
| | | 1434 | | private static bool IsMapLikeType(Type type) |
| | | 1435 | | { |
| | 2 | 1436 | | if (type.GetProperty("AdditionalProperties", BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenH |
| | | 1437 | | { |
| | 0 | 1438 | | return true; |
| | | 1439 | | } |
| | | 1440 | | |
| | 2 | 1441 | | var attributes = type.GetCustomAttributes(inherit: true); |
| | 8 | 1442 | | foreach (var attribute in attributes) |
| | | 1443 | | { |
| | 2 | 1444 | | if (attribute.GetType().Name.Equals("OpenApiPatternPropertiesAttribute", StringComparison.OrdinalIgnoreCase) |
| | | 1445 | | { |
| | 0 | 1446 | | return true; |
| | | 1447 | | } |
| | | 1448 | | } |
| | | 1449 | | |
| | 2 | 1450 | | return false; |
| | | 1451 | | } |
| | | 1452 | | |
| | | 1453 | | /// <summary> |
| | | 1454 | | /// Attempts to perform basic runtime conversions. |
| | | 1455 | | /// </summary> |
| | | 1456 | | /// <param name="value">The source value.</param> |
| | | 1457 | | /// <param name="targetType">The destination type.</param> |
| | | 1458 | | /// <param name="converted">The converted value when successful.</param> |
| | | 1459 | | /// <returns>True when conversion succeeds.</returns> |
| | | 1460 | | private static bool TryConvertSimple(object? value, Type targetType, out object? converted) |
| | | 1461 | | { |
| | 0 | 1462 | | converted = null; |
| | 0 | 1463 | | if (value is null) |
| | | 1464 | | { |
| | 0 | 1465 | | return false; |
| | | 1466 | | } |
| | | 1467 | | |
| | 0 | 1468 | | var valueType = value.GetType(); |
| | 0 | 1469 | | if (targetType.IsAssignableFrom(valueType)) |
| | | 1470 | | { |
| | 0 | 1471 | | converted = value; |
| | 0 | 1472 | | return true; |
| | | 1473 | | } |
| | | 1474 | | |
| | | 1475 | | try |
| | | 1476 | | { |
| | 0 | 1477 | | if (targetType.IsEnum) |
| | | 1478 | | { |
| | 0 | 1479 | | converted = value is string s |
| | 0 | 1480 | | ? Enum.Parse(targetType, s, ignoreCase: true) |
| | 0 | 1481 | | : Enum.ToObject(targetType, value); |
| | 0 | 1482 | | return true; |
| | | 1483 | | } |
| | | 1484 | | |
| | 0 | 1485 | | converted = Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture); |
| | 0 | 1486 | | return true; |
| | | 1487 | | } |
| | 0 | 1488 | | catch |
| | | 1489 | | { |
| | | 1490 | | try |
| | | 1491 | | { |
| | 0 | 1492 | | converted = LanguagePrimitives.ConvertTo(value, targetType, CultureInfo.InvariantCulture); |
| | 0 | 1493 | | return true; |
| | | 1494 | | } |
| | 0 | 1495 | | catch |
| | | 1496 | | { |
| | 0 | 1497 | | return false; |
| | | 1498 | | } |
| | | 1499 | | } |
| | 0 | 1500 | | } |
| | | 1501 | | |
| | | 1502 | | /// <summary> |
| | | 1503 | | /// Attempts to read a dictionary value with case-insensitive key matching. |
| | | 1504 | | /// </summary> |
| | | 1505 | | /// <typeparam name="T">The dictionary value type.</typeparam> |
| | | 1506 | | /// <param name="dict">The dictionary to read from.</param> |
| | | 1507 | | /// <param name="key">The key to search for.</param> |
| | | 1508 | | /// <param name="value">The matched value, if found.</param> |
| | | 1509 | | /// <returns>True when a matching key is found.</returns> |
| | | 1510 | | private static bool TryGetValueIgnoreCase<T>(IDictionary<string, T> dict, string key, out T? value) |
| | | 1511 | | { |
| | 9 | 1512 | | if (dict.TryGetValue(key, out value)) |
| | | 1513 | | { |
| | 6 | 1514 | | return true; |
| | | 1515 | | } |
| | | 1516 | | |
| | 14 | 1517 | | foreach (var kvp in dict) |
| | | 1518 | | { |
| | 4 | 1519 | | if (string.Equals(kvp.Key, key, StringComparison.OrdinalIgnoreCase)) |
| | | 1520 | | { |
| | 0 | 1521 | | value = kvp.Value; |
| | 0 | 1522 | | return true; |
| | | 1523 | | } |
| | | 1524 | | } |
| | | 1525 | | |
| | 3 | 1526 | | value = default; |
| | 3 | 1527 | | return false; |
| | 0 | 1528 | | } |
| | | 1529 | | |
| | | 1530 | | /// <summary> |
| | | 1531 | | /// Writes a response based on the specified media type. |
| | | 1532 | | /// </summary> |
| | | 1533 | | /// <param name="mediaType">The media type to use for the response.</param> |
| | | 1534 | | /// <param name="inputObject">The object to be written in the response body.</param> |
| | | 1535 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1536 | | /// <returns>A Task representing the asynchronous operation.</returns> |
| | | 1537 | | private Task WriteByMediaTypeAsync(string mediaType, object? inputObject, int statusCode) |
| | | 1538 | | { |
| | | 1539 | | // If you want, set Response.ContentType here once, centrally. |
| | 8 | 1540 | | ContentType = mediaType; |
| | | 1541 | | |
| | 8 | 1542 | | return mediaType switch |
| | 8 | 1543 | | { |
| | 6 | 1544 | | "application/json" => WriteJsonResponseAsync(inputObject, statusCode, mediaType), |
| | 0 | 1545 | | "application/yaml" => WriteYamlResponseAsync(inputObject, statusCode, mediaType), |
| | 0 | 1546 | | "application/xml" => WriteXmlResponseAsync(inputObject, statusCode, mediaType), |
| | 0 | 1547 | | "application/bson" => WriteBsonResponseAsync(inputObject, statusCode, mediaType), |
| | 0 | 1548 | | "application/cbor" => WriteCborResponseAsync(inputObject, statusCode, mediaType), |
| | 1 | 1549 | | "text/csv" => WriteCsvResponseAsync(inputObject, statusCode, mediaType), |
| | 0 | 1550 | | "application/x-www-form-urlencoded" => WriteFormUrlEncodedResponseAsync(inputObject, statusCode), |
| | 1 | 1551 | | _ => WriteTextResponseAsync(inputObject?.ToString() ?? string.Empty, statusCode), |
| | 8 | 1552 | | }; |
| | | 1553 | | } |
| | | 1554 | | |
| | | 1555 | | /// <summary> |
| | | 1556 | | /// Writes a CSV response with the specified input object, status code, content type, and optional CsvConfiguration. |
| | | 1557 | | /// </summary> |
| | | 1558 | | /// <param name="inputObject">The object to be converted to CSV.</param> |
| | | 1559 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1560 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1561 | | /// <param name="config">An optional CsvConfiguration to customize CSV output.</param> |
| | | 1562 | | public void WriteCsvResponse( |
| | | 1563 | | object? inputObject, |
| | | 1564 | | int statusCode = StatusCodes.Status200OK, |
| | | 1565 | | string? contentType = null, |
| | | 1566 | | CsvConfiguration? config = null) |
| | | 1567 | | { |
| | 2 | 1568 | | Action<CsvConfiguration>? tweaker = null; |
| | | 1569 | | |
| | 2 | 1570 | | if (config is not null) |
| | | 1571 | | { |
| | 1 | 1572 | | tweaker = target => |
| | 1 | 1573 | | { |
| | 90 | 1574 | | foreach (var prop in typeof(CsvConfiguration) |
| | 1 | 1575 | | .GetProperties(BindingFlags.Public | BindingFlags.Instance)) |
| | 1 | 1576 | | { |
| | 44 | 1577 | | if (prop.CanRead && prop.CanWrite) |
| | 1 | 1578 | | { |
| | 44 | 1579 | | var value = prop.GetValue(config); |
| | 44 | 1580 | | prop.SetValue(target, value); |
| | 1 | 1581 | | } |
| | 1 | 1582 | | } |
| | 2 | 1583 | | }; |
| | | 1584 | | } |
| | 2 | 1585 | | WriteCsvResponseAsync(inputObject, statusCode, contentType, tweaker).GetAwaiter().GetResult(); |
| | 2 | 1586 | | } |
| | | 1587 | | |
| | | 1588 | | /// <summary> |
| | | 1589 | | /// Asynchronously writes a CSV response with the specified input object, status code, content type, and optional co |
| | | 1590 | | /// </summary> |
| | | 1591 | | /// <param name="inputObject">The object to be converted to CSV.</param> |
| | | 1592 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1593 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1594 | | /// <param name="tweak">An optional action to tweak the CsvConfiguration.</param> |
| | | 1595 | | public async Task WriteCsvResponseAsync( |
| | | 1596 | | object? inputObject, |
| | | 1597 | | int statusCode = StatusCodes.Status200OK, |
| | | 1598 | | string? contentType = null, |
| | | 1599 | | Action<CsvConfiguration>? tweak = null) |
| | | 1600 | | { |
| | 4 | 1601 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1602 | | { |
| | 4 | 1603 | | Logger.Debug("Writing CSV response (async), StatusCode={StatusCode}, ContentType={ContentType}", |
| | 4 | 1604 | | statusCode, contentType); |
| | | 1605 | | } |
| | | 1606 | | |
| | | 1607 | | // Serialize inside a background task so heavy reflection never blocks the caller |
| | 4 | 1608 | | Body = await Task.Run(() => |
| | 4 | 1609 | | { |
| | 4 | 1610 | | var cfg = new CsvConfiguration(CultureInfo.InvariantCulture) |
| | 4 | 1611 | | { |
| | 4 | 1612 | | HasHeaderRecord = true, |
| | 4 | 1613 | | NewLine = Environment.NewLine |
| | 4 | 1614 | | }; |
| | 4 | 1615 | | tweak?.Invoke(cfg); // let the caller flirt with the config |
| | 4 | 1616 | | |
| | 4 | 1617 | | using var sw = new StringWriter(); |
| | 4 | 1618 | | using var csv = new CsvWriter(sw, cfg); |
| | 4 | 1619 | | |
| | 4 | 1620 | | // CsvHelper insists on an enumerable; wrap single objects so it stays happy |
| | 4 | 1621 | | if (inputObject is IEnumerable records and not string) |
| | 4 | 1622 | | { |
| | 4 | 1623 | | csv.WriteRecords(records); // whole collections (IEnumerable<T>) |
| | 4 | 1624 | | } |
| | 0 | 1625 | | else if (inputObject is not null) |
| | 4 | 1626 | | { |
| | 0 | 1627 | | csv.WriteRecords([inputObject]); // lone POCO |
| | 4 | 1628 | | } |
| | 4 | 1629 | | else |
| | 4 | 1630 | | { |
| | 0 | 1631 | | csv.WriteHeader<object>(); // nothing? write only headers for an empty file |
| | 4 | 1632 | | } |
| | 4 | 1633 | | |
| | 4 | 1634 | | return sw.ToString(); |
| | 8 | 1635 | | }).ConfigureAwait(false); |
| | | 1636 | | |
| | 4 | 1637 | | ContentType = string.IsNullOrEmpty(contentType) |
| | 4 | 1638 | | ? $"text/csv; charset={Encoding.WebName}" |
| | 4 | 1639 | | : contentType; |
| | 4 | 1640 | | StatusCode = statusCode; |
| | 4 | 1641 | | } |
| | | 1642 | | /// <summary> |
| | | 1643 | | /// Writes a YAML response with the specified input object, status code, and content type. |
| | | 1644 | | /// </summary> |
| | | 1645 | | /// <param name="inputObject">The object to be converted to YAML.</param> |
| | | 1646 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1647 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 1 | 1648 | | public void WriteYamlResponse(object? inputObject, int statusCode = StatusCodes.Status200OK, string? contentType = n |
| | | 1649 | | |
| | | 1650 | | /// <summary> |
| | | 1651 | | /// Asynchronously writes a YAML response with the specified input object, status code, and content type. |
| | | 1652 | | /// </summary> |
| | | 1653 | | /// <param name="inputObject">The object to be converted to YAML.</param> |
| | | 1654 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1655 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1656 | | public async Task WriteYamlResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? cont |
| | | 1657 | | { |
| | 3 | 1658 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1659 | | { |
| | 3 | 1660 | | Logger.Debug("Writing YAML response (async), StatusCode={StatusCode}, ContentType={ContentType}", statusCode |
| | | 1661 | | } |
| | | 1662 | | |
| | 6 | 1663 | | Body = await Task.Run(() => YamlHelper.ToYaml(inputObject)); |
| | 3 | 1664 | | ContentType = string.IsNullOrEmpty(contentType) ? $"application/yaml; charset={Encoding.WebName}" : contentType; |
| | 3 | 1665 | | StatusCode = statusCode; |
| | 3 | 1666 | | } |
| | | 1667 | | |
| | | 1668 | | /// <summary> |
| | | 1669 | | /// Writes an XML response with the specified input object, status code, and content type. |
| | | 1670 | | /// </summary> |
| | | 1671 | | /// <param name="inputObject">The object to be converted to XML.</param> |
| | | 1672 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1673 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1674 | | /// <param name="rootElementName">Optional custom XML root element name. Defaults to <c>Response</c>.</param> |
| | | 1675 | | /// <param name="compress">If true, emits compact XML (no indentation); if false (default) output is human readable. |
| | | 1676 | | public void WriteXmlResponse(object? inputObject, int statusCode = StatusCodes.Status200OK, string? contentType = nu |
| | 6 | 1677 | | => WriteXmlResponseAsync(inputObject, statusCode, contentType, rootElementName, compress).GetAwaiter().GetResult |
| | | 1678 | | |
| | | 1679 | | /// <summary> |
| | | 1680 | | /// Asynchronously writes an XML response with the specified input object, status code, and content type. |
| | | 1681 | | /// </summary> |
| | | 1682 | | /// <param name="inputObject">The object to be converted to XML.</param> |
| | | 1683 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1684 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1685 | | /// <param name="rootElementName">Optional custom XML root element name. Defaults to <c>Response</c>.</param> |
| | | 1686 | | /// <param name="compress">If true, emits compact XML (no indentation); if false (default) output is human readable. |
| | | 1687 | | public async Task WriteXmlResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? conte |
| | | 1688 | | { |
| | 8 | 1689 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1690 | | { |
| | 8 | 1691 | | Logger.Debug("Writing XML response (async), StatusCode={StatusCode}, ContentType={ContentType}", statusCode, |
| | | 1692 | | } |
| | | 1693 | | |
| | 8 | 1694 | | var root = string.IsNullOrWhiteSpace(rootElementName) ? "Response" : rootElementName.Trim(); |
| | 16 | 1695 | | var xml = await Task.Run(() => XmlHelper.ToXml(root, inputObject)); |
| | 8 | 1696 | | var saveOptions = compress ? SaveOptions.DisableFormatting : SaveOptions.None; |
| | 16 | 1697 | | Body = await Task.Run(() => xml.ToString(saveOptions)); |
| | 8 | 1698 | | ContentType = string.IsNullOrEmpty(contentType) ? $"application/xml; charset={Encoding.WebName}" : contentType; |
| | 8 | 1699 | | StatusCode = statusCode; |
| | 8 | 1700 | | } |
| | | 1701 | | /// <summary> |
| | | 1702 | | /// Writes a text response with the specified input object, status code, and content type. |
| | | 1703 | | /// </summary> |
| | | 1704 | | /// <param name="inputObject">The object to be converted to a text response.</param> |
| | | 1705 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1706 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1707 | | public void WriteTextResponse(object? inputObject, int statusCode = StatusCodes.Status200OK, string? contentType = n |
| | 8 | 1708 | | WriteTextResponseAsync(inputObject, statusCode, contentType).GetAwaiter().GetResult(); |
| | | 1709 | | |
| | | 1710 | | /// <summary> |
| | | 1711 | | /// Asynchronously writes a text response with the specified input object, status code, and content type. |
| | | 1712 | | /// </summary> |
| | | 1713 | | /// <param name="inputObject">The object to be converted to a text response.</param> |
| | | 1714 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1715 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1716 | | public async Task WriteTextResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? cont |
| | | 1717 | | { |
| | 36 | 1718 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1719 | | { |
| | 31 | 1720 | | Logger.Debug("Writing text response (async), StatusCode={StatusCode}, ContentType={ContentType}", statusCode |
| | | 1721 | | } |
| | | 1722 | | |
| | 36 | 1723 | | if (inputObject is null) |
| | | 1724 | | { |
| | 0 | 1725 | | throw new ArgumentNullException(nameof(inputObject), "Input object cannot be null for text response."); |
| | | 1726 | | } |
| | | 1727 | | |
| | 72 | 1728 | | Body = await Task.Run(() => inputObject?.ToString() ?? string.Empty); |
| | 36 | 1729 | | ContentType = string.IsNullOrEmpty(contentType) ? $"text/plain; charset={Encoding.WebName}" : contentType; |
| | 36 | 1730 | | StatusCode = statusCode; |
| | 36 | 1731 | | } |
| | | 1732 | | |
| | | 1733 | | /// <summary> |
| | | 1734 | | /// Writes a form-urlencoded response with the specified input object, status code, and optional content type. |
| | | 1735 | | /// Automatically converts the input object to a Dictionary{string, string} using <see cref="ObjectToDictionaryConve |
| | | 1736 | | /// </summary> |
| | | 1737 | | /// <param name="inputObject">The object to be converted to form-urlencoded data. Can be a dictionary, enumerable, o |
| | | 1738 | | /// <param name="statusCode">The HTTP status code for the response. Defaults to 200 OK.</param> |
| | | 1739 | | public void WriteFormUrlEncodedResponse(object? inputObject, int statusCode = StatusCodes.Status200OK) => |
| | 8 | 1740 | | WriteFormUrlEncodedResponseAsync(inputObject, statusCode).GetAwaiter().GetResult(); |
| | | 1741 | | |
| | | 1742 | | /// <summary> |
| | | 1743 | | /// Asynchronously writes a form-urlencoded response with the specified input object, status code, and optional cont |
| | | 1744 | | /// Automatically converts the input object to a Dictionary{string, string} using <see cref="ObjectToDictionaryConve |
| | | 1745 | | /// </summary> |
| | | 1746 | | /// <param name="inputObject">The object to be converted to form-urlencoded data. Can be a dictionary, enumerable, o |
| | | 1747 | | /// <param name="statusCode">The HTTP status code for the response. Defaults to 200 OK.</param> |
| | | 1748 | | public async Task WriteFormUrlEncodedResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK) |
| | | 1749 | | { |
| | 11 | 1750 | | if (inputObject is null) |
| | | 1751 | | { |
| | 2 | 1752 | | throw new ArgumentNullException(nameof(inputObject), "Input object cannot be null for form-urlencoded respon |
| | | 1753 | | } |
| | | 1754 | | |
| | 9 | 1755 | | var dictionary = ObjectToDictionaryConverter.ToDictionary(inputObject); |
| | 9 | 1756 | | var formContent = new FormUrlEncodedContent(dictionary); |
| | 9 | 1757 | | var encodedString = await formContent.ReadAsStringAsync(); |
| | | 1758 | | |
| | 9 | 1759 | | await WriteTextResponseAsync(encodedString, statusCode, "application/x-www-form-urlencoded"); |
| | 9 | 1760 | | } |
| | | 1761 | | |
| | | 1762 | | /// <summary> |
| | | 1763 | | /// Writes an HTTP redirect response with the specified URL and optional message. |
| | | 1764 | | /// </summary> |
| | | 1765 | | /// <param name="url">The URL to redirect to.</param> |
| | | 1766 | | /// <param name="message">An optional message to include in the response body.</param> |
| | | 1767 | | public void WriteRedirectResponse(string url, string? message = null) |
| | | 1768 | | { |
| | 6 | 1769 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1770 | | { |
| | 5 | 1771 | | Logger.Debug("Writing redirect response, StatusCode={StatusCode}, Location={Location}", StatusCode, url); |
| | | 1772 | | } |
| | | 1773 | | |
| | 6 | 1774 | | if (string.IsNullOrEmpty(url)) |
| | | 1775 | | { |
| | 0 | 1776 | | throw new ArgumentNullException(nameof(url), "URL cannot be null for redirect response."); |
| | | 1777 | | } |
| | | 1778 | | // framework hook |
| | 6 | 1779 | | RedirectUrl = url; |
| | | 1780 | | |
| | | 1781 | | // HTTP status + Location header |
| | 6 | 1782 | | StatusCode = StatusCodes.Status302Found; |
| | 6 | 1783 | | Headers["Location"] = url; |
| | | 1784 | | |
| | 6 | 1785 | | if (message is not null) |
| | | 1786 | | { |
| | | 1787 | | // include a body |
| | 1 | 1788 | | Body = message; |
| | 1 | 1789 | | ContentType = $"text/plain; charset={Encoding.WebName}"; |
| | | 1790 | | } |
| | | 1791 | | else |
| | | 1792 | | { |
| | | 1793 | | // no body: clear any existing body/headers |
| | 5 | 1794 | | Body = null; |
| | | 1795 | | //ContentType = null; |
| | 5 | 1796 | | _ = Headers.Remove("Content-Length"); |
| | | 1797 | | } |
| | 5 | 1798 | | } |
| | | 1799 | | |
| | | 1800 | | /// <summary> |
| | | 1801 | | /// Writes a binary response with the specified data, status code, and content type. |
| | | 1802 | | /// </summary> |
| | | 1803 | | /// <param name="data">The binary data to send in the response.</param> |
| | | 1804 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1805 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1806 | | public void WriteBinaryResponse(byte[] data, int statusCode = StatusCodes.Status200OK, string contentType = "applica |
| | | 1807 | | { |
| | 1 | 1808 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1809 | | { |
| | 1 | 1810 | | Logger.Debug("Writing binary response, StatusCode={StatusCode}, ContentType={ContentType}", statusCode, cont |
| | | 1811 | | } |
| | | 1812 | | |
| | 1 | 1813 | | Body = data ?? throw new ArgumentNullException(nameof(data), "Data cannot be null for binary response."); |
| | 1 | 1814 | | ContentType = contentType; |
| | 1 | 1815 | | StatusCode = statusCode; |
| | 1 | 1816 | | } |
| | | 1817 | | /// <summary> |
| | | 1818 | | /// Writes a stream response with the specified stream, status code, and content type. |
| | | 1819 | | /// </summary> |
| | | 1820 | | /// <param name="stream">The stream to send in the response.</param> |
| | | 1821 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1822 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1823 | | public void WriteStreamResponse(Stream stream, int statusCode = StatusCodes.Status200OK, string contentType = "appli |
| | | 1824 | | { |
| | 3 | 1825 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1826 | | { |
| | 3 | 1827 | | Logger.Debug("Writing stream response, StatusCode={StatusCode}, ContentType={ContentType}", statusCode, cont |
| | | 1828 | | } |
| | | 1829 | | |
| | 3 | 1830 | | Body = stream; |
| | 3 | 1831 | | ContentType = contentType; |
| | 3 | 1832 | | StatusCode = statusCode; |
| | 3 | 1833 | | } |
| | | 1834 | | #endregion |
| | | 1835 | | |
| | | 1836 | | #region Error Responses |
| | | 1837 | | /// <summary> |
| | | 1838 | | /// Structured payload for error responses. |
| | | 1839 | | /// </summary> |
| | | 1840 | | internal record ErrorPayload |
| | | 1841 | | { |
| | 34 | 1842 | | public string Error { get; init; } = default!; |
| | 35 | 1843 | | public string? Details { get; init; } |
| | 37 | 1844 | | public string? Exception { get; init; } |
| | 36 | 1845 | | public string? StackTrace { get; init; } |
| | 68 | 1846 | | public int Status { get; init; } |
| | 34 | 1847 | | public string Reason { get; init; } = default!; |
| | 34 | 1848 | | public string Timestamp { get; init; } = default!; |
| | 27 | 1849 | | public string? Path { get; init; } |
| | 27 | 1850 | | public string? Method { get; init; } |
| | | 1851 | | } |
| | | 1852 | | |
| | | 1853 | | /// <summary> |
| | | 1854 | | /// Write an error response with a custom message. |
| | | 1855 | | /// Chooses JSON/YAML/XML/plain-text based on override → Accept → default JSON. |
| | | 1856 | | /// </summary> |
| | | 1857 | | public async Task WriteErrorResponseAsync( |
| | | 1858 | | string message, |
| | | 1859 | | int statusCode = StatusCodes.Status500InternalServerError, |
| | | 1860 | | string? contentType = null, |
| | | 1861 | | string? details = null) |
| | | 1862 | | { |
| | 14 | 1863 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1864 | | { |
| | 14 | 1865 | | Logger.Debug("Writing error response, StatusCode={StatusCode}, ContentType={ContentType}, Message={Message}" |
| | 14 | 1866 | | statusCode, contentType, message); |
| | | 1867 | | } |
| | | 1868 | | |
| | 14 | 1869 | | if (string.IsNullOrWhiteSpace(message)) |
| | | 1870 | | { |
| | 0 | 1871 | | throw new ArgumentNullException(nameof(message)); |
| | | 1872 | | } |
| | | 1873 | | |
| | 14 | 1874 | | Logger.Warning("Writing error response with status {StatusCode}: {Message}", statusCode, message); |
| | | 1875 | | |
| | 14 | 1876 | | var payload = new ErrorPayload |
| | 14 | 1877 | | { |
| | 14 | 1878 | | Error = message, |
| | 14 | 1879 | | Details = details, |
| | 14 | 1880 | | Exception = null, |
| | 14 | 1881 | | StackTrace = null, |
| | 14 | 1882 | | Status = statusCode, |
| | 14 | 1883 | | Reason = ReasonPhrases.GetReasonPhrase(statusCode), |
| | 14 | 1884 | | Timestamp = DateTime.UtcNow.ToString("o"), |
| | 14 | 1885 | | Path = Request?.Path, |
| | 14 | 1886 | | Method = Request?.Method |
| | 14 | 1887 | | }; |
| | | 1888 | | |
| | 14 | 1889 | | await WriteFormattedErrorResponseAsync(payload, contentType); |
| | 14 | 1890 | | } |
| | | 1891 | | |
| | | 1892 | | /// <summary> |
| | | 1893 | | /// Writes an error response with a custom message. |
| | | 1894 | | /// Chooses JSON/YAML/XML/plain-text based on override → Accept → default JSON. |
| | | 1895 | | /// </summary> |
| | | 1896 | | /// <param name="message">The error message to include in the response.</param> |
| | | 1897 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1898 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1899 | | /// <param name="details">Optional details to include in the response.</param> |
| | | 1900 | | public void WriteErrorResponse( |
| | | 1901 | | string message, |
| | | 1902 | | int statusCode = StatusCodes.Status500InternalServerError, |
| | | 1903 | | string? contentType = null, |
| | 1 | 1904 | | string? details = null) => WriteErrorResponseAsync(message, statusCode, contentType, details).GetAwaiter().GetResu |
| | | 1905 | | |
| | | 1906 | | /// <summary> |
| | | 1907 | | /// Asynchronously writes an error response based on an exception. |
| | | 1908 | | /// Chooses JSON/YAML/XML/plain-text based on override → Accept → default JSON. |
| | | 1909 | | /// </summary> |
| | | 1910 | | /// <param name="ex">The exception to report.</param> |
| | | 1911 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1912 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1913 | | /// <param name="includeStack">Whether to include the stack trace in the response.</param> |
| | | 1914 | | public async Task WriteErrorResponseAsync( |
| | | 1915 | | Exception ex, |
| | | 1916 | | int statusCode = StatusCodes.Status500InternalServerError, |
| | | 1917 | | string? contentType = null, |
| | | 1918 | | bool includeStack = true) |
| | | 1919 | | { |
| | 3 | 1920 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1921 | | { |
| | 3 | 1922 | | Logger.Debug("Writing error response from exception, StatusCode={StatusCode}, ContentType={ContentType}, Inc |
| | 3 | 1923 | | statusCode, contentType, includeStack); |
| | | 1924 | | } |
| | | 1925 | | |
| | 3 | 1926 | | ArgumentNullException.ThrowIfNull(ex); |
| | | 1927 | | |
| | 3 | 1928 | | Logger.Warning(ex, "Writing error response with status {StatusCode}", statusCode); |
| | | 1929 | | |
| | 3 | 1930 | | var payload = new ErrorPayload |
| | 3 | 1931 | | { |
| | 3 | 1932 | | Error = ex.Message, |
| | 3 | 1933 | | Details = null, |
| | 3 | 1934 | | Exception = ex.GetType().Name, |
| | 3 | 1935 | | StackTrace = includeStack ? ex.ToString() : null, |
| | 3 | 1936 | | Status = statusCode, |
| | 3 | 1937 | | Reason = ReasonPhrases.GetReasonPhrase(statusCode), |
| | 3 | 1938 | | Timestamp = DateTime.UtcNow.ToString("o"), |
| | 3 | 1939 | | Path = Request?.Path, |
| | 3 | 1940 | | Method = Request?.Method |
| | 3 | 1941 | | }; |
| | | 1942 | | |
| | 3 | 1943 | | await WriteFormattedErrorResponseAsync(payload, contentType); |
| | 3 | 1944 | | } |
| | | 1945 | | /// <summary> |
| | | 1946 | | /// Writes an error response based on an exception. |
| | | 1947 | | /// Chooses JSON/YAML/XML/plain-text based on override → Accept → default JSON. |
| | | 1948 | | /// </summary> |
| | | 1949 | | /// <param name="ex">The exception to report.</param> |
| | | 1950 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1951 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 1952 | | /// <param name="includeStack">Whether to include the stack trace in the response.</param> |
| | | 1953 | | public void WriteErrorResponse( |
| | | 1954 | | Exception ex, |
| | | 1955 | | int statusCode = StatusCodes.Status500InternalServerError, |
| | | 1956 | | string? contentType = null, |
| | 1 | 1957 | | bool includeStack = true) => WriteErrorResponseAsync(ex, statusCode, contentType, includeStack).GetAwaiter() |
| | | 1958 | | |
| | | 1959 | | /// <summary> |
| | | 1960 | | /// Internal dispatcher: serializes the payload according to the chosen content-type. |
| | | 1961 | | /// </summary> |
| | | 1962 | | private async Task WriteFormattedErrorResponseAsync(ErrorPayload payload, string? contentType = null) |
| | | 1963 | | { |
| | 17 | 1964 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1965 | | { |
| | 17 | 1966 | | Logger.Debug("Writing formatted error response, ContentType={ContentType}, Status={Status}", contentType, pa |
| | | 1967 | | } |
| | | 1968 | | |
| | 17 | 1969 | | if (string.IsNullOrWhiteSpace(contentType)) |
| | | 1970 | | { |
| | 15 | 1971 | | _ = Request.Headers.TryGetValue("Accept", out var acceptHeader); |
| | 15 | 1972 | | contentType = (acceptHeader ?? "text/plain") |
| | 15 | 1973 | | .ToLowerInvariant(); |
| | | 1974 | | } |
| | 17 | 1975 | | if (contentType.Contains("json")) |
| | | 1976 | | { |
| | 6 | 1977 | | await WriteJsonResponseAsync(payload, payload.Status); |
| | | 1978 | | } |
| | 11 | 1979 | | else if (contentType.Contains("yaml") || contentType.Contains("yml")) |
| | | 1980 | | { |
| | 2 | 1981 | | await WriteYamlResponseAsync(payload, payload.Status); |
| | | 1982 | | } |
| | 9 | 1983 | | else if (contentType.Contains("xml")) |
| | | 1984 | | { |
| | 2 | 1985 | | await WriteXmlResponseAsync(payload, payload.Status); |
| | | 1986 | | } |
| | | 1987 | | else |
| | | 1988 | | { |
| | | 1989 | | // Plain-text fallback |
| | 7 | 1990 | | var lines = new List<string> |
| | 7 | 1991 | | { |
| | 7 | 1992 | | $"Status: {payload.Status} ({payload.Reason})", |
| | 7 | 1993 | | $"Error: {payload.Error}", |
| | 7 | 1994 | | $"Time: {payload.Timestamp}" |
| | 7 | 1995 | | }; |
| | | 1996 | | |
| | 7 | 1997 | | if (!string.IsNullOrWhiteSpace(payload.Details)) |
| | | 1998 | | { |
| | 1 | 1999 | | lines.Add("Details:\n" + payload.Details); |
| | | 2000 | | } |
| | | 2001 | | |
| | 7 | 2002 | | if (!string.IsNullOrWhiteSpace(payload.Exception)) |
| | | 2003 | | { |
| | 3 | 2004 | | lines.Add($"Exception: {payload.Exception}"); |
| | | 2005 | | } |
| | | 2006 | | |
| | 7 | 2007 | | if (!string.IsNullOrWhiteSpace(payload.StackTrace)) |
| | | 2008 | | { |
| | 2 | 2009 | | lines.Add("StackTrace:\n" + payload.StackTrace); |
| | | 2010 | | } |
| | | 2011 | | |
| | 7 | 2012 | | var text = string.Join("\n", lines); |
| | 7 | 2013 | | await WriteTextResponseAsync(text, payload.Status, "text/plain"); |
| | | 2014 | | } |
| | 17 | 2015 | | } |
| | | 2016 | | |
| | | 2017 | | #endregion |
| | | 2018 | | #region HTML Response Helpers |
| | | 2019 | | |
| | | 2020 | | /// <summary> |
| | | 2021 | | /// Renders a template string by replacing placeholders in the format {{key}} with corresponding values from the pro |
| | | 2022 | | /// </summary> |
| | | 2023 | | /// <param name="template">The template string containing placeholders.</param> |
| | | 2024 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 2025 | | /// <returns>The rendered string with placeholders replaced by variable values.</returns> |
| | | 2026 | | private string RenderInlineTemplate( |
| | | 2027 | | string template, |
| | | 2028 | | IReadOnlyDictionary<string, object?> vars) |
| | | 2029 | | { |
| | 2 | 2030 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2031 | | { |
| | 2 | 2032 | | Logger.Debug("Rendering inline template, TemplateLength={TemplateLength}, VarsCount={VarsCount}", |
| | 2 | 2033 | | template?.Length ?? 0, vars?.Count ?? 0); |
| | | 2034 | | } |
| | | 2035 | | |
| | 2 | 2036 | | if (string.IsNullOrEmpty(template)) |
| | | 2037 | | { |
| | 0 | 2038 | | return string.Empty; |
| | | 2039 | | } |
| | | 2040 | | |
| | 2 | 2041 | | if (vars is null || vars.Count == 0) |
| | | 2042 | | { |
| | 0 | 2043 | | return template; |
| | | 2044 | | } |
| | | 2045 | | |
| | 2 | 2046 | | var render = RenderInline(template, vars); |
| | | 2047 | | |
| | 2 | 2048 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2049 | | { |
| | 2 | 2050 | | Logger.Debug("Rendered template length: {RenderedLength}", render.Length); |
| | | 2051 | | } |
| | | 2052 | | |
| | 2 | 2053 | | return render; |
| | | 2054 | | } |
| | | 2055 | | |
| | | 2056 | | /// <summary> |
| | | 2057 | | /// Renders a template string by replacing placeholders in the format {{key}} with corresponding values from the pro |
| | | 2058 | | /// </summary> |
| | | 2059 | | /// <param name="template">The template string containing placeholders.</param> |
| | | 2060 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 2061 | | /// <returns>The rendered string with placeholders replaced by variable values.</returns> |
| | | 2062 | | private static string RenderInline(string template, IReadOnlyDictionary<string, object?> vars) |
| | | 2063 | | { |
| | 2 | 2064 | | var sb = new StringBuilder(template.Length); |
| | | 2065 | | |
| | | 2066 | | // Iterate through the template |
| | 2 | 2067 | | var i = 0; |
| | 39 | 2068 | | while (i < template.Length) |
| | | 2069 | | { |
| | | 2070 | | // opening “{{” |
| | 37 | 2071 | | if (template[i] == '{' && i + 1 < template.Length && template[i + 1] == '{') |
| | | 2072 | | { |
| | 3 | 2073 | | var start = i + 2; // after “{{” |
| | 3 | 2074 | | var end = template.IndexOf("}}", start, StringComparison.Ordinal); |
| | | 2075 | | |
| | 3 | 2076 | | if (end > start) // found closing “}}” |
| | | 2077 | | { |
| | 3 | 2078 | | var rawKey = template[start..end].Trim(); |
| | | 2079 | | |
| | 3 | 2080 | | if (TryResolveValue(rawKey, vars, out var value) && value is not null) |
| | | 2081 | | { |
| | 3 | 2082 | | _ = sb.Append(value); // append resolved value |
| | | 2083 | | } |
| | | 2084 | | else |
| | | 2085 | | { |
| | 0 | 2086 | | _ = sb.Append("{{").Append(rawKey).Append("}}"); // leave it as-is if unknown |
| | | 2087 | | } |
| | | 2088 | | |
| | 3 | 2089 | | i = end + 2; // jump past the “}}” |
| | 3 | 2090 | | continue; |
| | | 2091 | | } |
| | | 2092 | | } |
| | | 2093 | | |
| | | 2094 | | // ordinary character |
| | 34 | 2095 | | _ = sb.Append(template[i]); |
| | 34 | 2096 | | i++; // move to the next character |
| | | 2097 | | } |
| | 2 | 2098 | | return sb.ToString(); |
| | | 2099 | | } |
| | | 2100 | | |
| | | 2101 | | /// <summary> |
| | | 2102 | | /// Resolves a dotted path like “Request.Path” through nested dictionaries |
| | | 2103 | | /// and/or object properties (case-insensitive). |
| | | 2104 | | /// </summary> |
| | | 2105 | | private static bool TryResolveValue( |
| | | 2106 | | string path, |
| | | 2107 | | IReadOnlyDictionary<string, object?> root, |
| | | 2108 | | out object? value) |
| | | 2109 | | { |
| | 3 | 2110 | | value = null; |
| | | 2111 | | |
| | 3 | 2112 | | if (string.IsNullOrWhiteSpace(path)) |
| | | 2113 | | { |
| | 0 | 2114 | | return false; |
| | | 2115 | | } |
| | | 2116 | | |
| | 3 | 2117 | | object? current = root; |
| | 16 | 2118 | | foreach (var segment in path.Split('.')) |
| | | 2119 | | { |
| | 5 | 2120 | | if (current is null) |
| | | 2121 | | { |
| | 0 | 2122 | | return false; |
| | | 2123 | | } |
| | | 2124 | | |
| | | 2125 | | // ① Handle dictionary look-ups (IReadOnlyDictionary or IDictionary) |
| | 5 | 2126 | | if (current is IReadOnlyDictionary<string, object?> roDict) |
| | | 2127 | | { |
| | 3 | 2128 | | if (!roDict.TryGetValue(segment, out current)) |
| | | 2129 | | { |
| | 0 | 2130 | | return false; |
| | | 2131 | | } |
| | | 2132 | | |
| | | 2133 | | continue; |
| | | 2134 | | } |
| | | 2135 | | |
| | 2 | 2136 | | if (current is IDictionary dict) |
| | | 2137 | | { |
| | 0 | 2138 | | if (!dict.Contains(segment)) |
| | | 2139 | | { |
| | 0 | 2140 | | return false; |
| | | 2141 | | } |
| | | 2142 | | |
| | 0 | 2143 | | current = dict[segment]; |
| | 0 | 2144 | | continue; |
| | | 2145 | | } |
| | | 2146 | | |
| | | 2147 | | // ② Handle property look-ups via reflection |
| | 2 | 2148 | | var prop = current.GetType().GetProperty( |
| | 2 | 2149 | | segment, |
| | 2 | 2150 | | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); |
| | | 2151 | | |
| | 2 | 2152 | | if (prop is null) |
| | | 2153 | | { |
| | 0 | 2154 | | return false; |
| | | 2155 | | } |
| | | 2156 | | |
| | 2 | 2157 | | current = prop.GetValue(current); |
| | | 2158 | | } |
| | | 2159 | | |
| | 3 | 2160 | | value = current; |
| | 3 | 2161 | | return true; |
| | | 2162 | | } |
| | | 2163 | | |
| | | 2164 | | /// <summary> |
| | | 2165 | | /// Attempts to revalidate the cache based on ETag and Last-Modified headers. |
| | | 2166 | | /// If the resource is unchanged, sets the response status to 304 Not Modified. |
| | | 2167 | | /// Returns true if a 304 response was written, false otherwise. |
| | | 2168 | | /// </summary> |
| | | 2169 | | /// <param name="payload">The payload to validate.</param> |
| | | 2170 | | /// <param name="etag">The ETag header value.</param> |
| | | 2171 | | /// <param name="weakETag">Indicates if the ETag is a weak ETag.</param> |
| | | 2172 | | /// <param name="lastModified">The Last-Modified header value.</param> |
| | | 2173 | | /// <returns>True if a 304 response was written, false otherwise.</returns> |
| | | 2174 | | public bool RevalidateCache(object? payload, |
| | | 2175 | | string? etag = null, |
| | | 2176 | | bool weakETag = false, |
| | 0 | 2177 | | DateTimeOffset? lastModified = null) => CacheRevalidation.TryWrite304(Context, payload, etag, weakETag, lastModif |
| | | 2178 | | |
| | | 2179 | | /// <summary> |
| | | 2180 | | /// Asynchronously writes an HTML response, rendering the provided template string and replacing placeholders with v |
| | | 2181 | | /// </summary> |
| | | 2182 | | /// <param name="template">The HTML template string containing placeholders.</param> |
| | | 2183 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 2184 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 2185 | | public async Task WriteHtmlResponseAsync( |
| | | 2186 | | string template, |
| | | 2187 | | IReadOnlyDictionary<string, object?>? vars, |
| | | 2188 | | int statusCode = 200) |
| | | 2189 | | { |
| | 2 | 2190 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2191 | | { |
| | 2 | 2192 | | Logger.Debug("Writing HTML response (async), StatusCode={StatusCode}, TemplateLength={TemplateLength}", stat |
| | | 2193 | | } |
| | | 2194 | | |
| | 2 | 2195 | | if (vars is null || vars.Count == 0) |
| | | 2196 | | { |
| | 0 | 2197 | | await WriteTextResponseAsync(template, statusCode, "text/html"); |
| | | 2198 | | } |
| | | 2199 | | else |
| | | 2200 | | { |
| | 2 | 2201 | | await WriteTextResponseAsync(RenderInlineTemplate(template, vars), statusCode, "text/html"); |
| | | 2202 | | } |
| | 2 | 2203 | | } |
| | | 2204 | | |
| | | 2205 | | /// <summary> |
| | | 2206 | | /// Asynchronously writes an HTML response, rendering the provided template byte array and replacing placeholders wi |
| | | 2207 | | /// </summary> |
| | | 2208 | | /// <param name="template">The HTML template byte array.</param> |
| | | 2209 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 2210 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 2211 | | /// <returns>A task representing the asynchronous operation.</returns> |
| | | 2212 | | public async Task WriteHtmlResponseAsync( |
| | | 2213 | | byte[] template, |
| | | 2214 | | IReadOnlyDictionary<string, object?>? vars, |
| | 0 | 2215 | | int statusCode = 200) => await WriteHtmlResponseAsync(Encoding.GetString(template), vars, statusCode); |
| | | 2216 | | |
| | | 2217 | | /// <summary> |
| | | 2218 | | /// Writes an HTML response, rendering the provided template byte array and replacing placeholders with values from |
| | | 2219 | | /// </summary> |
| | | 2220 | | /// <param name="template">The HTML template byte array.</param> |
| | | 2221 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 2222 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 2223 | | public void WriteHtmlResponse( |
| | | 2224 | | byte[] template, |
| | | 2225 | | IReadOnlyDictionary<string, object?>? vars, |
| | 0 | 2226 | | int statusCode = 200) => WriteHtmlResponseAsync(Encoding.GetString(template), vars, statusCode).GetAwaiter().Ge |
| | | 2227 | | |
| | | 2228 | | /// <summary> |
| | | 2229 | | /// Asynchronously reads an HTML file, merges in placeholders from the provided dictionary, and writes the result as |
| | | 2230 | | /// </summary> |
| | | 2231 | | /// <param name="filePath">The path to the HTML file to read.</param> |
| | | 2232 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 2233 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 2234 | | public async Task WriteHtmlResponseFromFileAsync( |
| | | 2235 | | string filePath, |
| | | 2236 | | IReadOnlyDictionary<string, object?> vars, |
| | | 2237 | | int statusCode = 200) |
| | | 2238 | | { |
| | 1 | 2239 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2240 | | { |
| | 1 | 2241 | | Logger.Debug("Writing HTML response from file (async), FilePath={FilePath}, StatusCode={StatusCode}", filePa |
| | | 2242 | | } |
| | | 2243 | | |
| | 1 | 2244 | | if (!File.Exists(filePath)) |
| | | 2245 | | { |
| | 0 | 2246 | | WriteTextResponse($"<!-- File not found: {filePath} -->", 404, "text/html"); |
| | 0 | 2247 | | return; |
| | | 2248 | | } |
| | | 2249 | | |
| | 1 | 2250 | | var template = await File.ReadAllTextAsync(filePath); |
| | 1 | 2251 | | WriteHtmlResponseAsync(template, vars, statusCode).GetAwaiter().GetResult(); |
| | 1 | 2252 | | } |
| | | 2253 | | |
| | | 2254 | | /// <summary> |
| | | 2255 | | /// Renders the given HTML string with placeholders and writes it as a response. |
| | | 2256 | | /// </summary> |
| | | 2257 | | /// <param name="template">The HTML template string containing placeholders.</param> |
| | | 2258 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 2259 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 2260 | | public void WriteHtmlResponse( |
| | | 2261 | | string template, |
| | | 2262 | | IReadOnlyDictionary<string, object?>? vars, |
| | 0 | 2263 | | int statusCode = 200) => WriteHtmlResponseAsync(template, vars, statusCode).GetAwaiter().GetResult(); |
| | | 2264 | | |
| | | 2265 | | /// <summary> |
| | | 2266 | | /// Reads an .html file, merges in placeholders, and writes it. |
| | | 2267 | | /// </summary> |
| | | 2268 | | public void WriteHtmlResponseFromFile( |
| | | 2269 | | string filePath, |
| | | 2270 | | IReadOnlyDictionary<string, object?> vars, |
| | 0 | 2271 | | int statusCode = 200) => WriteHtmlResponseFromFileAsync(filePath, vars, statusCode).GetAwaiter().GetResult(); |
| | | 2272 | | |
| | | 2273 | | /// <summary> |
| | | 2274 | | /// Writes only the specified HTTP status code, clearing any body or content type. |
| | | 2275 | | /// </summary> |
| | | 2276 | | /// <param name="statusCode">The HTTP status code to write.</param> |
| | | 2277 | | public void WriteStatusOnly(int statusCode) |
| | | 2278 | | { |
| | | 2279 | | // Clear any body indicators so StatusCodePages can run |
| | 1 | 2280 | | ContentType = null; |
| | 1 | 2281 | | StatusCode = statusCode; |
| | 1 | 2282 | | Body = null; |
| | 1 | 2283 | | } |
| | | 2284 | | #endregion |
| | | 2285 | | |
| | | 2286 | | #region Apply to HttpResponse |
| | | 2287 | | |
| | | 2288 | | /// <summary> |
| | | 2289 | | /// Applies the current KestrunResponse to the specified HttpResponse, setting status, headers, cookies, and writing |
| | | 2290 | | /// </summary> |
| | | 2291 | | /// <param name="response">The HttpResponse to apply the response to.</param> |
| | | 2292 | | /// <returns>A task representing the asynchronous operation.</returns> |
| | | 2293 | | public async Task ApplyTo(HttpResponse response) |
| | | 2294 | | { |
| | 36 | 2295 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2296 | | { |
| | 24 | 2297 | | Logger.Debug("Applying KestrunResponse to HttpResponse, StatusCode={StatusCode}, ContentType={ContentType}, |
| | 24 | 2298 | | StatusCode, ContentType, Body?.GetType().Name ?? "null"); |
| | | 2299 | | } |
| | | 2300 | | |
| | 36 | 2301 | | if (response.StatusCode == StatusCodes.Status304NotModified) |
| | | 2302 | | { |
| | 0 | 2303 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2304 | | { |
| | 0 | 2305 | | Logger.Debug("Response already has status code 304 Not Modified, skipping ApplyTo"); |
| | | 2306 | | } |
| | 0 | 2307 | | return; |
| | | 2308 | | } |
| | 36 | 2309 | | if (response.HasStarted) |
| | | 2310 | | { |
| | 0 | 2311 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2312 | | { |
| | 0 | 2313 | | Logger.Debug("HttpResponse has already started, skipping KestrunResponse.ApplyTo()."); |
| | | 2314 | | } |
| | 0 | 2315 | | return; |
| | | 2316 | | } |
| | 36 | 2317 | | if (!string.IsNullOrEmpty(RedirectUrl)) |
| | | 2318 | | { |
| | 3 | 2319 | | response.Redirect(RedirectUrl); |
| | 3 | 2320 | | return; |
| | | 2321 | | } |
| | | 2322 | | |
| | | 2323 | | try |
| | | 2324 | | { |
| | 33 | 2325 | | EnsureStatus(response); |
| | | 2326 | | // Apply headers, cookies, caching |
| | 33 | 2327 | | ApplyHeadersAndCookies(response); |
| | | 2328 | | // Caching |
| | 33 | 2329 | | ApplyCachingHeaders(response); |
| | | 2330 | | // Callbacks |
| | 33 | 2331 | | await TryEnqueueCallbacks(); |
| | | 2332 | | // Body |
| | 33 | 2333 | | await WriteResponseContent(response); |
| | 33 | 2334 | | } |
| | 0 | 2335 | | catch (Exception ex) |
| | | 2336 | | { |
| | 0 | 2337 | | Logger.Error(ex, "Error applying KestrunResponse to HttpResponse"); |
| | | 2338 | | // Optionally, you can log the exception or handle it as needed |
| | 0 | 2339 | | throw; |
| | | 2340 | | } |
| | 36 | 2341 | | } |
| | | 2342 | | |
| | | 2343 | | /// <summary> |
| | | 2344 | | /// Applies the body content to the HTTP response. If the body is not null, it ensures the content type, |
| | | 2345 | | /// applies the content disposition header, and writes the body asynchronously. If the body is null, |
| | | 2346 | | /// it clears the content type and content length if the response has not started. Logs debug information about the |
| | | 2347 | | /// </summary> |
| | | 2348 | | /// <param name="response"> The HTTP response to which the body content will be applied. </param> |
| | | 2349 | | /// <returns> A task representing the asynchronous operation. </returns> |
| | | 2350 | | private async Task WriteResponseContent(HttpResponse response) |
| | | 2351 | | { |
| | 33 | 2352 | | if (Body is not null) |
| | | 2353 | | { |
| | 28 | 2354 | | EnsureContentType(response); |
| | 28 | 2355 | | ApplyContentDispositionHeader(response); |
| | 28 | 2356 | | await WriteBodyAsync(response).ConfigureAwait(false); |
| | | 2357 | | } |
| | | 2358 | | else |
| | | 2359 | | { |
| | 5 | 2360 | | if (!response.HasStarted && string.IsNullOrEmpty(response.ContentType)) |
| | | 2361 | | { |
| | 3 | 2362 | | response.ContentType = null; |
| | | 2363 | | } |
| | | 2364 | | |
| | 5 | 2365 | | if (!response.HasStarted) |
| | | 2366 | | { |
| | 5 | 2367 | | response.ContentLength = null; |
| | | 2368 | | } |
| | 5 | 2369 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2370 | | { |
| | 4 | 2371 | | Logger.Debug("Status-only: HasStarted={HasStarted} CL={CL} CT='{CT}'", |
| | 4 | 2372 | | response.HasStarted, response.ContentLength, response.ContentType); |
| | | 2373 | | } |
| | | 2374 | | } |
| | 33 | 2375 | | } |
| | | 2376 | | |
| | | 2377 | | /// <summary> |
| | | 2378 | | /// Attempts to enqueue any registered callback requests using the ICallbackDispatcher service. |
| | | 2379 | | /// </summary> |
| | | 2380 | | private async ValueTask TryEnqueueCallbacks() |
| | | 2381 | | { |
| | 33 | 2382 | | if (CallbackPlan.Count == 0) |
| | | 2383 | | { |
| | 32 | 2384 | | return; |
| | | 2385 | | } |
| | | 2386 | | |
| | | 2387 | | // Prevent multiple enqueues |
| | 1 | 2388 | | if (Interlocked.Exchange(ref CallbacksEnqueuedFlag, 1) == 1) |
| | | 2389 | | { |
| | 0 | 2390 | | return; |
| | | 2391 | | } |
| | | 2392 | | |
| | 1 | 2393 | | if (Logger.IsEnabled(LogEventLevel.Information)) |
| | | 2394 | | { |
| | 1 | 2395 | | Logger.Information("Enqueuing {Count} callbacks for dispatch.", CallbackPlan.Count); |
| | | 2396 | | } |
| | | 2397 | | |
| | | 2398 | | try |
| | | 2399 | | { |
| | 1 | 2400 | | var httpCtx = KrContext.HttpContext; |
| | | 2401 | | |
| | | 2402 | | // Resolve DI services while request is alive |
| | 1 | 2403 | | var dispatcher = httpCtx.RequestServices.GetService<ICallbackDispatcher>(); |
| | 1 | 2404 | | if (dispatcher is null) |
| | | 2405 | | { |
| | 1 | 2406 | | Logger.Warning("Callbacks present but no ICallbackDispatcher registered. Count={Count}", CallbackPlan.Co |
| | 1 | 2407 | | return; |
| | | 2408 | | } |
| | | 2409 | | |
| | 0 | 2410 | | var urlResolver = httpCtx.RequestServices.GetRequiredService<ICallbackUrlResolver>(); |
| | 0 | 2411 | | var serializer = httpCtx.RequestServices.GetRequiredService<ICallbackBodySerializer>(); |
| | 0 | 2412 | | var options = httpCtx.RequestServices.GetService<CallbackDispatchOptions>() ?? new CallbackDispatchOptions() |
| | | 2413 | | |
| | 0 | 2414 | | foreach (var plan in CallbackPlan) |
| | | 2415 | | { |
| | | 2416 | | try |
| | | 2417 | | { |
| | 0 | 2418 | | var req = CallbackRequestFactory.FromPlan(plan, KrContext, urlResolver, serializer, options); |
| | | 2419 | | |
| | 0 | 2420 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2421 | | { |
| | 0 | 2422 | | Logger.Debug("Enqueue callback. CallbackId={CallbackId} Url={Url}", req.CallbackId, req.TargetUr |
| | | 2423 | | } |
| | | 2424 | | |
| | 0 | 2425 | | await dispatcher.EnqueueAsync(req, CancellationToken.None).ConfigureAwait(false); |
| | 0 | 2426 | | } |
| | 0 | 2427 | | catch (Exception ex) |
| | | 2428 | | { |
| | 0 | 2429 | | Logger.Error(ex, "Failed to enqueue callback. CallbackId={CallbackId}", plan.CallbackId); |
| | 0 | 2430 | | } |
| | 0 | 2431 | | } |
| | 0 | 2432 | | } |
| | 0 | 2433 | | catch (Exception ex) |
| | | 2434 | | { |
| | 0 | 2435 | | Logger.Error(ex, "Unexpected error while scheduling callbacks."); |
| | 0 | 2436 | | } |
| | 33 | 2437 | | } |
| | | 2438 | | |
| | | 2439 | | /// <summary> |
| | | 2440 | | /// Ensures the HTTP response has the correct status code and content type. |
| | | 2441 | | /// </summary> |
| | | 2442 | | /// <param name="response">The HTTP response to apply the status and content type to.</param> |
| | | 2443 | | private void EnsureContentType(HttpResponse response) |
| | | 2444 | | { |
| | 28 | 2445 | | if (ContentType != response.ContentType) |
| | | 2446 | | { |
| | 28 | 2447 | | if (!string.IsNullOrEmpty(ContentType) && |
| | 28 | 2448 | | IsTextBasedContentType(ContentType) && |
| | 28 | 2449 | | !ContentType.Contains("charset=", StringComparison.OrdinalIgnoreCase)) |
| | | 2450 | | { |
| | 6 | 2451 | | ContentType = ContentType.TrimEnd(';') + $"; charset={AcceptCharset.WebName}"; |
| | | 2452 | | } |
| | 28 | 2453 | | response.ContentType = ContentType; |
| | | 2454 | | } |
| | 28 | 2455 | | } |
| | | 2456 | | |
| | | 2457 | | /// <summary> |
| | | 2458 | | /// Ensures the HTTP response has the correct status code. |
| | | 2459 | | /// </summary> |
| | | 2460 | | /// <param name="response">The HTTP response to apply the status code to.</param> |
| | | 2461 | | private void EnsureStatus(HttpResponse response) |
| | | 2462 | | { |
| | 33 | 2463 | | if (StatusCode != response.StatusCode) |
| | | 2464 | | { |
| | 5 | 2465 | | response.StatusCode = StatusCode; |
| | | 2466 | | } |
| | 33 | 2467 | | } |
| | | 2468 | | |
| | | 2469 | | /// <summary> |
| | | 2470 | | /// Adds caching headers to the response based on the provided CacheControlHeaderValue options. |
| | | 2471 | | /// </summary> |
| | | 2472 | | /// <param name="response">The HTTP response to apply caching headers to.</param> |
| | | 2473 | | /// <exception cref="ArgumentNullException">Thrown when options is null.</exception> |
| | | 2474 | | public void ApplyCachingHeaders(HttpResponse response) |
| | | 2475 | | { |
| | 33 | 2476 | | if (CacheControl is not null) |
| | | 2477 | | { |
| | 1 | 2478 | | response.Headers.CacheControl = CacheControl.ToString(); |
| | | 2479 | | } |
| | 33 | 2480 | | } |
| | | 2481 | | |
| | | 2482 | | /// <summary> |
| | | 2483 | | /// Applies the Content-Disposition header to the HTTP response. |
| | | 2484 | | /// </summary> |
| | | 2485 | | /// <param name="response">The HTTP response to apply the header to.</param> |
| | | 2486 | | private void ApplyContentDispositionHeader(HttpResponse response) |
| | | 2487 | | { |
| | 28 | 2488 | | if (ContentDisposition.Type == ContentDispositionType.NoContentDisposition) |
| | | 2489 | | { |
| | 26 | 2490 | | return; |
| | | 2491 | | } |
| | | 2492 | | |
| | 2 | 2493 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2494 | | { |
| | 2 | 2495 | | Logger.Debug("Setting Content-Disposition header, Type={Type}, FileName={FileName}", |
| | 2 | 2496 | | ContentDisposition.Type, ContentDisposition.FileName); |
| | | 2497 | | } |
| | | 2498 | | |
| | 2 | 2499 | | var dispositionValue = ContentDisposition.Type switch |
| | 2 | 2500 | | { |
| | 2 | 2501 | | ContentDispositionType.Attachment => "attachment", |
| | 0 | 2502 | | ContentDispositionType.Inline => "inline", |
| | 0 | 2503 | | _ => throw new InvalidOperationException("Invalid Content-Disposition type") |
| | 2 | 2504 | | }; |
| | | 2505 | | |
| | 2 | 2506 | | if (string.IsNullOrEmpty(ContentDisposition.FileName) && Body is IFileInfo fi) |
| | | 2507 | | { |
| | | 2508 | | // default filename: use the file's name |
| | 1 | 2509 | | ContentDisposition.FileName = fi.Name; |
| | | 2510 | | } |
| | | 2511 | | |
| | 2 | 2512 | | if (!string.IsNullOrEmpty(ContentDisposition.FileName)) |
| | | 2513 | | { |
| | 2 | 2514 | | var escapedFileName = WebUtility.UrlEncode(ContentDisposition.FileName); |
| | 2 | 2515 | | dispositionValue += $"; filename=\"{escapedFileName}\""; |
| | | 2516 | | } |
| | | 2517 | | |
| | 2 | 2518 | | response.Headers.Append("Content-Disposition", dispositionValue); |
| | 2 | 2519 | | } |
| | | 2520 | | |
| | | 2521 | | /// <summary> |
| | | 2522 | | /// Applies headers and cookies to the HTTP response. |
| | | 2523 | | /// </summary> |
| | | 2524 | | /// <param name="response">The HTTP response to apply the headers and cookies to.</param> |
| | | 2525 | | private void ApplyHeadersAndCookies(HttpResponse response) |
| | | 2526 | | { |
| | 33 | 2527 | | if (Headers is not null) |
| | | 2528 | | { |
| | 66 | 2529 | | foreach (var kv in Headers) |
| | | 2530 | | { |
| | 0 | 2531 | | response.Headers[kv.Key] = kv.Value; |
| | | 2532 | | } |
| | | 2533 | | } |
| | 33 | 2534 | | if (Cookies is not null) |
| | | 2535 | | { |
| | 6 | 2536 | | foreach (var cookie in Cookies) |
| | | 2537 | | { |
| | 2 | 2538 | | response.Headers.Append("Set-Cookie", cookie); |
| | | 2539 | | } |
| | | 2540 | | } |
| | 33 | 2541 | | } |
| | | 2542 | | |
| | | 2543 | | /// <summary> |
| | | 2544 | | /// Writes the response body to the HTTP response. |
| | | 2545 | | /// </summary> |
| | | 2546 | | /// <param name="response">The HTTP response to write to.</param> |
| | | 2547 | | /// <returns>A task representing the asynchronous operation.</returns> |
| | | 2548 | | private async Task WriteBodyAsync(HttpResponse response) |
| | | 2549 | | { |
| | 28 | 2550 | | var bodyValue = Body; // capture to avoid nullability warnings when mutated in default |
| | | 2551 | | switch (bodyValue) |
| | | 2552 | | { |
| | | 2553 | | case IFileInfo fileInfo: |
| | 1 | 2554 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2555 | | { |
| | 1 | 2556 | | Logger.Debug("Sending file {FileName} (Length={Length})", fileInfo.Name, fileInfo.Length); |
| | | 2557 | | } |
| | 1 | 2558 | | response.ContentLength = fileInfo.Length; |
| | 1 | 2559 | | response.Headers.LastModified = fileInfo.LastModified.ToString("R"); |
| | 1 | 2560 | | await response.SendFileAsync( |
| | 1 | 2561 | | file: fileInfo, |
| | 1 | 2562 | | offset: 0, |
| | 1 | 2563 | | count: fileInfo.Length, |
| | 1 | 2564 | | cancellationToken: response.HttpContext.RequestAborted |
| | 1 | 2565 | | ); |
| | 1 | 2566 | | break; |
| | | 2567 | | |
| | | 2568 | | case byte[] bytes: |
| | 1 | 2569 | | response.ContentLength = bytes.LongLength; |
| | 1 | 2570 | | await response.Body.WriteAsync(bytes, response.HttpContext.RequestAborted); |
| | 1 | 2571 | | await response.Body.FlushAsync(response.HttpContext.RequestAborted); |
| | 1 | 2572 | | break; |
| | | 2573 | | |
| | | 2574 | | case Stream stream: |
| | 2 | 2575 | | var seekable = stream.CanSeek; |
| | 2 | 2576 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2577 | | { |
| | 2 | 2578 | | Logger.Debug("Sending stream (seekable={Seekable}, len={Len})", |
| | 2 | 2579 | | seekable, seekable ? stream.Length : -1); |
| | | 2580 | | } |
| | 2 | 2581 | | if (seekable) |
| | | 2582 | | { |
| | 1 | 2583 | | response.ContentLength = stream.Length; |
| | 1 | 2584 | | stream.Position = 0; |
| | | 2585 | | } |
| | | 2586 | | else |
| | | 2587 | | { |
| | 1 | 2588 | | response.ContentLength = null; |
| | | 2589 | | } |
| | | 2590 | | |
| | | 2591 | | const int BufferSize = 64 * 1024; // 64 KB |
| | 2 | 2592 | | var buffer = ArrayPool<byte>.Shared.Rent(BufferSize); |
| | | 2593 | | try |
| | | 2594 | | { |
| | | 2595 | | int bytesRead; |
| | 4 | 2596 | | while ((bytesRead = await stream.ReadAsync(buffer.AsMemory(0, BufferSize), response.HttpContext.Requ |
| | | 2597 | | { |
| | 2 | 2598 | | await response.Body.WriteAsync(buffer.AsMemory(0, bytesRead), response.HttpContext.RequestAborte |
| | | 2599 | | } |
| | 2 | 2600 | | } |
| | | 2601 | | finally |
| | | 2602 | | { |
| | 2 | 2603 | | ArrayPool<byte>.Shared.Return(buffer); |
| | | 2604 | | } |
| | 2 | 2605 | | await response.Body.FlushAsync(response.HttpContext.RequestAborted); |
| | 2 | 2606 | | break; |
| | | 2607 | | |
| | | 2608 | | case string str: |
| | 24 | 2609 | | var data = AcceptCharset.GetBytes(str); |
| | 24 | 2610 | | response.ContentLength = data.Length; |
| | 24 | 2611 | | await response.Body.WriteAsync(data, response.HttpContext.RequestAborted); |
| | 24 | 2612 | | await response.Body.FlushAsync(response.HttpContext.RequestAborted); |
| | 24 | 2613 | | break; |
| | | 2614 | | |
| | | 2615 | | default: |
| | 0 | 2616 | | var bodyType = bodyValue?.GetType().Name ?? "null"; |
| | 0 | 2617 | | Body = "Unsupported body type: " + bodyType; |
| | 0 | 2618 | | Logger.Warning("Unsupported body type: {BodyType}", bodyType); |
| | 0 | 2619 | | response.StatusCode = StatusCodes.Status500InternalServerError; |
| | 0 | 2620 | | response.ContentType = "text/plain; charset=utf-8"; |
| | 0 | 2621 | | response.ContentLength = Body.ToString()?.Length ?? null; |
| | | 2622 | | break; |
| | | 2623 | | } |
| | 28 | 2624 | | } |
| | | 2625 | | #endregion |
| | | 2626 | | } |