| | | 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; |
| | | 10 | | using Serilog.Events; |
| | | 11 | | using System.Buffers; |
| | | 12 | | using Microsoft.Extensions.FileProviders; |
| | | 13 | | using Microsoft.AspNetCore.WebUtilities; |
| | | 14 | | using System.Net; |
| | | 15 | | using MongoDB.Bson; |
| | | 16 | | using Kestrun.Utilities; |
| | | 17 | | using System.Collections; |
| | | 18 | | using CsvHelper.Configuration; |
| | | 19 | | using System.Globalization; |
| | | 20 | | using CsvHelper; |
| | | 21 | | using System.Reflection; |
| | | 22 | | using Microsoft.Net.Http.Headers; |
| | | 23 | | using Kestrun.Utilities.Yaml; |
| | | 24 | | using Kestrun.Hosting.Options; |
| | | 25 | | using Kestrun.Callback; |
| | | 26 | | |
| | | 27 | | namespace Kestrun.Models; |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Represents an HTTP response in the Kestrun framework, providing methods to write various content types and manage he |
| | | 31 | | /// </summary> |
| | | 32 | | /// <remarks> |
| | | 33 | | /// Initializes a new instance of the <see cref="KestrunResponse"/> class with the specified request and optional body a |
| | | 34 | | /// </remarks> |
| | | 35 | | public class KestrunResponse |
| | | 36 | | { |
| | | 37 | | /// <summary> |
| | | 38 | | /// Flag indicating whether callbacks have already been enqueued. |
| | | 39 | | /// </summary> |
| | | 40 | | internal int CallbacksEnqueuedFlag; // 0 = no, 1 = yes |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Gets the list of callback requests associated with this response. |
| | | 44 | | /// </summary> |
| | 178 | 45 | | public List<CallBackExecutionPlan> CallbackPlan { get; } = []; |
| | | 46 | | |
| | 0 | 47 | | private Serilog.ILogger Logger => KrContext.Host.Logger; |
| | | 48 | | /// <summary> |
| | | 49 | | /// Gets the route options associated with this response. |
| | | 50 | | /// </summary> |
| | 0 | 51 | | public MapRouteOptions MapRouteOptions => KrContext.MapRouteOptions; |
| | | 52 | | /// <summary> |
| | | 53 | | /// Gets the associated KestrunContext for this response. |
| | | 54 | | /// </summary> |
| | 591 | 55 | | public required KestrunContext KrContext { get; init; } |
| | | 56 | | |
| | | 57 | | /// <summary> |
| | | 58 | | /// Gets the KestrunHost associated with this response. |
| | | 59 | | /// </summary> |
| | 0 | 60 | | public Hosting.KestrunHost Host => KrContext.Host; |
| | | 61 | | /// <summary> |
| | | 62 | | /// A set of MIME types that are considered text-based for response content. |
| | | 63 | | /// </summary> |
| | 1 | 64 | | public static readonly HashSet<string> TextBasedMimeTypes = |
| | 1 | 65 | | new(StringComparer.OrdinalIgnoreCase) |
| | 1 | 66 | | { |
| | 1 | 67 | | "application/json", |
| | 1 | 68 | | "application/xml", |
| | 1 | 69 | | "application/javascript", |
| | 1 | 70 | | "application/xhtml+xml", |
| | 1 | 71 | | "application/x-www-form-urlencoded", |
| | 1 | 72 | | "application/yaml", |
| | 1 | 73 | | "application/graphql" |
| | 1 | 74 | | }; |
| | | 75 | | |
| | | 76 | | /// <summary> |
| | | 77 | | /// Initializes a new instance of the <see cref="KestrunResponse"/> class. |
| | | 78 | | /// </summary> |
| | | 79 | | /// <param name="krContext">The associated <see cref="KestrunContext"/> for this response.</param> |
| | | 80 | | /// <param name="bodyAsyncThreshold">The threshold in bytes for using async body write operations. Defaults to 8192. |
| | | 81 | | [SetsRequiredMembers] |
| | 146 | 82 | | public KestrunResponse(KestrunContext krContext, int bodyAsyncThreshold = 8192) |
| | | 83 | | { |
| | 146 | 84 | | KrContext = krContext; |
| | 146 | 85 | | BodyAsyncThreshold = bodyAsyncThreshold; |
| | 146 | 86 | | Request = KrContext.Request ?? throw new ArgumentNullException(nameof(KrContext)); |
| | 146 | 87 | | AcceptCharset = KrContext.Request.Headers.TryGetValue("Accept-Charset", out var value) ? Encoding.GetEncoding(va |
| | 146 | 88 | | StatusCode = KrContext.HttpContext.Response.StatusCode; |
| | 146 | 89 | | } |
| | | 90 | | |
| | | 91 | | /// <summary> |
| | | 92 | | /// Gets the <see cref="HttpContext"/> associated with the response. |
| | | 93 | | /// </summary> |
| | 0 | 94 | | public HttpContext Context => KrContext.HttpContext; |
| | | 95 | | /// <summary> |
| | | 96 | | /// Gets or sets the HTTP status code for the response. |
| | | 97 | | /// </summary> |
| | 309 | 98 | | public int StatusCode { get; set; } |
| | | 99 | | /// <summary> |
| | | 100 | | /// Gets or sets the collection of HTTP headers for the response. |
| | | 101 | | /// </summary> |
| | 216 | 102 | | public Dictionary<string, string> Headers { get; set; } = []; |
| | | 103 | | /// <summary> |
| | | 104 | | /// Gets or sets the MIME content type of the response. |
| | | 105 | | /// </summary> |
| | 417 | 106 | | public string? ContentType { get; set; } = "text/plain"; |
| | | 107 | | /// <summary> |
| | | 108 | | /// Gets or sets the body of the response, which can be a string, byte array, stream, or file info. |
| | | 109 | | /// </summary> |
| | 231 | 110 | | public object? Body { get; set; } |
| | | 111 | | /// <summary> |
| | | 112 | | /// Gets or sets the URL to redirect the response to, if an HTTP redirect is required. |
| | | 113 | | /// </summary> |
| | 61 | 114 | | public string? RedirectUrl { get; set; } // For HTTP redirects |
| | | 115 | | /// <summary> |
| | | 116 | | /// Gets or sets the list of Set-Cookie header values for the response. |
| | | 117 | | /// </summary> |
| | 31 | 118 | | public List<string>? Cookies { get; set; } // For Set-Cookie headers |
| | | 119 | | |
| | | 120 | | /// <summary> |
| | | 121 | | /// Text encoding for textual MIME types. |
| | | 122 | | /// </summary> |
| | 187 | 123 | | public Encoding Encoding { get; set; } = Encoding.UTF8; |
| | | 124 | | |
| | | 125 | | /// <summary> |
| | | 126 | | /// Content-Disposition header value. |
| | | 127 | | /// </summary> |
| | 186 | 128 | | public ContentDispositionOptions ContentDisposition { get; set; } = new ContentDispositionOptions(); |
| | | 129 | | /// <summary> |
| | | 130 | | /// Gets the associated KestrunRequest for this response. |
| | | 131 | | /// </summary> |
| | 188 | 132 | | public required KestrunRequest Request { get; init; } |
| | | 133 | | |
| | | 134 | | /// <summary> |
| | | 135 | | /// Global text encoding for all responses. Defaults to UTF-8. |
| | | 136 | | /// </summary> |
| | 173 | 137 | | public required Encoding AcceptCharset { get; init; } |
| | | 138 | | |
| | | 139 | | /// <summary> |
| | | 140 | | /// If the response body is larger than this threshold (in bytes), async write will be used. |
| | | 141 | | /// </summary> |
| | 146 | 142 | | public required int BodyAsyncThreshold { get; init; } |
| | | 143 | | |
| | | 144 | | /// <summary> |
| | | 145 | | /// Cache-Control header value for the response. |
| | | 146 | | /// </summary> |
| | 31 | 147 | | public CacheControlHeaderValue? CacheControl { get; set; } |
| | | 148 | | |
| | | 149 | | #region Constructors |
| | | 150 | | #endregion |
| | | 151 | | |
| | | 152 | | #region Helpers |
| | | 153 | | private static string GetSafeCurrentDirectoryOrBaseDirectory() |
| | | 154 | | { |
| | | 155 | | try |
| | | 156 | | { |
| | 2 | 157 | | return Directory.GetCurrentDirectory(); |
| | | 158 | | } |
| | 0 | 159 | | catch (Exception ex) when (ex is IOException |
| | 0 | 160 | | or UnauthorizedAccessException |
| | 0 | 161 | | or DirectoryNotFoundException |
| | 0 | 162 | | or FileNotFoundException) |
| | | 163 | | { |
| | | 164 | | // On Unix/macOS, getcwd() can throw if the process CWD was deleted. |
| | | 165 | | // We use AppContext.BaseDirectory as a stable fallback to avoid crashing in diagnostics |
| | | 166 | | // and when resolving relative paths. |
| | 0 | 167 | | return AppContext.BaseDirectory; |
| | | 168 | | } |
| | 2 | 169 | | } |
| | | 170 | | |
| | 2 | 171 | | private static string GetSafeCurrentDirectoryForLogging() => GetSafeCurrentDirectoryOrBaseDirectory(); |
| | | 172 | | |
| | | 173 | | /// <summary> |
| | | 174 | | /// Retrieves the value of the specified header from the response headers. |
| | | 175 | | /// </summary> |
| | | 176 | | /// <param name="key">The name of the header to retrieve.</param> |
| | | 177 | | /// <returns>The value of the header if found; otherwise, null.</returns> |
| | 0 | 178 | | public string? GetHeader(string key) => Headers.TryGetValue(key, out var value) ? value : null; |
| | | 179 | | |
| | | 180 | | /// <summary> |
| | | 181 | | /// Determines whether the specified content type is text-based or supports a charset. |
| | | 182 | | /// </summary> |
| | | 183 | | /// <param name="type">The MIME content type to check.</param> |
| | | 184 | | /// <returns>True if the content type is text-based; otherwise, false.</returns> |
| | | 185 | | public static bool IsTextBasedContentType(string type) |
| | | 186 | | { |
| | 34 | 187 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 188 | | { |
| | 33 | 189 | | Log.Debug("Checking if content type is text-based: {ContentType}", type); |
| | | 190 | | } |
| | | 191 | | |
| | | 192 | | // Check if the content type is text-based or has a charset |
| | 34 | 193 | | if (string.IsNullOrEmpty(type)) |
| | | 194 | | { |
| | 1 | 195 | | return false; |
| | | 196 | | } |
| | | 197 | | |
| | 33 | 198 | | if (type.StartsWith("text/", StringComparison.OrdinalIgnoreCase)) |
| | | 199 | | { |
| | 20 | 200 | | return true; |
| | | 201 | | } |
| | 13 | 202 | | if (type == "application/x-www-form-urlencoded") |
| | | 203 | | { |
| | 0 | 204 | | return true; |
| | | 205 | | } |
| | | 206 | | |
| | | 207 | | // Include structured types using XML or JSON suffixes |
| | 13 | 208 | | if (type.EndsWith("xml", StringComparison.OrdinalIgnoreCase) || |
| | 13 | 209 | | type.EndsWith("json", StringComparison.OrdinalIgnoreCase) || |
| | 13 | 210 | | type.EndsWith("yaml", StringComparison.OrdinalIgnoreCase) || |
| | 13 | 211 | | type.EndsWith("csv", StringComparison.OrdinalIgnoreCase)) |
| | | 212 | | { |
| | 4 | 213 | | return true; |
| | | 214 | | } |
| | | 215 | | |
| | | 216 | | // Common application types where charset makes sense |
| | 9 | 217 | | return TextBasedMimeTypes.Contains(type); |
| | | 218 | | } |
| | | 219 | | /// <summary> |
| | | 220 | | /// Adds callback parameters for the specified callback ID, body, and parameters. |
| | | 221 | | /// </summary> |
| | | 222 | | /// <param name="callbackId">The identifier for the callback</param> |
| | | 223 | | /// <param name="bodyParameterName">The name of the body parameter, if any</param> |
| | | 224 | | /// <param name="parameters">The parameters for the callback</param> |
| | | 225 | | public void AddCallbackParameters(string callbackId, string? bodyParameterName, Dictionary<string, object?> paramete |
| | | 226 | | { |
| | 0 | 227 | | if (MapRouteOptions.CallbackPlan is null || MapRouteOptions.CallbackPlan.Count == 0) |
| | | 228 | | { |
| | 0 | 229 | | return; |
| | | 230 | | } |
| | 0 | 231 | | var plan = MapRouteOptions.CallbackPlan.FirstOrDefault(p => p.CallbackId == callbackId); |
| | 0 | 232 | | if (plan is null) |
| | | 233 | | { |
| | 0 | 234 | | Logger.Warning("CallbackPlan '{id}' not found.", callbackId); |
| | 0 | 235 | | return; |
| | | 236 | | } |
| | | 237 | | // Create a new execution plan |
| | 0 | 238 | | var newExecutionPlan = new CallBackExecutionPlan( |
| | 0 | 239 | | CallbackId: callbackId, |
| | 0 | 240 | | Plan: plan, |
| | 0 | 241 | | BodyParameterName: bodyParameterName, |
| | 0 | 242 | | Parameters: parameters |
| | 0 | 243 | | ); |
| | | 244 | | |
| | 0 | 245 | | CallbackPlan.Add(newExecutionPlan); |
| | 0 | 246 | | } |
| | | 247 | | #endregion |
| | | 248 | | |
| | | 249 | | #region Response Writers |
| | | 250 | | /// <summary> |
| | | 251 | | /// Writes a file response with the specified file path, content type, and HTTP status code. |
| | | 252 | | /// </summary> |
| | | 253 | | /// <param name="filePath">The path to the file to be sent in the response.</param> |
| | | 254 | | /// <param name="contentType">The MIME type of the file content.</param> |
| | | 255 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 256 | | public void WriteFileResponse( |
| | | 257 | | string? filePath, |
| | | 258 | | string? contentType, |
| | | 259 | | int statusCode = StatusCodes.Status200OK |
| | | 260 | | ) |
| | | 261 | | { |
| | 2 | 262 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 263 | | { |
| | 2 | 264 | | Log.Debug("Writing file response,FilePath={FilePath} StatusCode={StatusCode}, ContentType={ContentType}, Cur |
| | 2 | 265 | | filePath, statusCode, contentType, GetSafeCurrentDirectoryForLogging()); |
| | | 266 | | } |
| | | 267 | | |
| | 2 | 268 | | if (string.IsNullOrEmpty(filePath)) |
| | | 269 | | { |
| | 0 | 270 | | throw new ArgumentException("File path cannot be null or empty.", nameof(filePath)); |
| | | 271 | | } |
| | | 272 | | |
| | | 273 | | // IMPORTANT: |
| | | 274 | | // - Path.GetFullPath(relative) uses the process CWD. |
| | | 275 | | // - If the CWD is missing/deleted (can occur in CI/test scenarios), GetFullPath can fail. |
| | | 276 | | // Resolve relative paths against a safe, existing base directory instead. |
| | 2 | 277 | | var fullPath = Path.IsPathRooted(filePath) |
| | 2 | 278 | | ? Path.GetFullPath(filePath) |
| | 2 | 279 | | : Path.GetFullPath(filePath, GetSafeCurrentDirectoryOrBaseDirectory()); |
| | | 280 | | |
| | 2 | 281 | | if (!File.Exists(fullPath)) |
| | | 282 | | { |
| | 1 | 283 | | StatusCode = StatusCodes.Status404NotFound; |
| | 1 | 284 | | Body = $"File not found: {filePath}"; |
| | 1 | 285 | | ContentType = $"text/plain; charset={Encoding.WebName}"; |
| | 1 | 286 | | return; |
| | | 287 | | } |
| | | 288 | | |
| | | 289 | | // 2. Extract the directory to use as the "root" |
| | 1 | 290 | | var directory = Path.GetDirectoryName(fullPath) |
| | 1 | 291 | | ?? throw new InvalidOperationException("Could not determine directory from file path"); |
| | | 292 | | |
| | 1 | 293 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 294 | | { |
| | 1 | 295 | | Log.Debug("Serving file: {FilePath}", fullPath); |
| | | 296 | | } |
| | | 297 | | |
| | | 298 | | // Create a physical file provider for the directory |
| | 1 | 299 | | var physicalProvider = new PhysicalFileProvider(directory); |
| | 1 | 300 | | var fi = physicalProvider.GetFileInfo(Path.GetFileName(fullPath)); |
| | 1 | 301 | | var provider = new FileExtensionContentTypeProvider(); |
| | 1 | 302 | | contentType ??= provider.TryGetContentType(fullPath, out var ct) |
| | 1 | 303 | | ? ct |
| | 1 | 304 | | : "application/octet-stream"; |
| | 1 | 305 | | Body = fi; |
| | | 306 | | |
| | | 307 | | // headers & metadata |
| | 1 | 308 | | StatusCode = statusCode; |
| | 1 | 309 | | ContentType = contentType; |
| | 1 | 310 | | Log.Debug("File response prepared: FileName={FileName}, Length={Length}, ContentType={ContentType}", |
| | 1 | 311 | | fi.Name, fi.Length, ContentType); |
| | 1 | 312 | | } |
| | | 313 | | |
| | | 314 | | /// <summary> |
| | | 315 | | /// Writes a JSON response with the specified input object and HTTP status code. |
| | | 316 | | /// </summary> |
| | | 317 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 318 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | 6 | 319 | | public void WriteJsonResponse(object? inputObject, int statusCode = StatusCodes.Status200OK) => WriteJsonResponseAsy |
| | | 320 | | |
| | | 321 | | /// <summary> |
| | | 322 | | /// Asynchronously writes a JSON response with the specified input object and HTTP status code. |
| | | 323 | | /// </summary> |
| | | 324 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 325 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 326 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 6 | 327 | | public async Task WriteJsonResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? cont |
| | | 328 | | |
| | | 329 | | /// <summary> |
| | | 330 | | /// Writes a JSON response using the specified input object and serializer settings. |
| | | 331 | | /// </summary> |
| | | 332 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 333 | | /// <param name="serializerOptions">The options to use for JSON serialization.</param> |
| | | 334 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 335 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 0 | 336 | | public void WriteJsonResponse(object? inputObject, JsonSerializerOptions serializerOptions, int statusCode = StatusC |
| | | 337 | | |
| | | 338 | | /// <summary> |
| | | 339 | | /// Asynchronously writes a JSON response using the specified input object and serializer settings. |
| | | 340 | | /// </summary> |
| | | 341 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 342 | | /// <param name="serializerOptions">The options to use for JSON serialization.</param> |
| | | 343 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 344 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 345 | | public async Task WriteJsonResponseAsync(object? inputObject, JsonSerializerOptions serializerOptions, int statusCod |
| | | 346 | | { |
| | 16 | 347 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 348 | | { |
| | 16 | 349 | | Log.Debug("Writing JSON response (async), StatusCode={StatusCode}, ContentType={ContentType}", statusCode, c |
| | | 350 | | } |
| | | 351 | | |
| | 16 | 352 | | ArgumentNullException.ThrowIfNull(serializerOptions); |
| | | 353 | | |
| | 16 | 354 | | var sanitizedPayload = PayloadSanitizer.Sanitize(inputObject); |
| | 32 | 355 | | Body = await Task.Run(() => JsonSerializer.Serialize(sanitizedPayload, serializerOptions)); |
| | 16 | 356 | | ContentType = string.IsNullOrEmpty(contentType) ? $"application/json; charset={Encoding.WebName}" : contentType; |
| | 16 | 357 | | StatusCode = statusCode; |
| | 16 | 358 | | } |
| | | 359 | | /// <summary> |
| | | 360 | | /// Writes a JSON response with the specified input object, serialization depth, compression option, status code, an |
| | | 361 | | /// </summary> |
| | | 362 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 363 | | /// <param name="depth">The maximum depth for JSON serialization.</param> |
| | | 364 | | /// <param name="compress">Whether to compress the JSON output (no indentation).</param> |
| | | 365 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 366 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 1 | 367 | | public void WriteJsonResponse(object? inputObject, int depth, bool compress, int statusCode = StatusCodes.Status200O |
| | | 368 | | |
| | | 369 | | /// <summary> |
| | | 370 | | /// Asynchronously writes a JSON response with the specified input object, serialization depth, compression option, |
| | | 371 | | /// </summary> |
| | | 372 | | /// <param name="inputObject">The object to be converted to JSON.</param> |
| | | 373 | | /// <param name="depth">The maximum depth for JSON serialization.</param> |
| | | 374 | | /// <param name="compress">Whether to compress the JSON output (no indentation).</param> |
| | | 375 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 376 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 377 | | public async Task WriteJsonResponseAsync(object? inputObject, int depth, bool compress, int statusCode = StatusCodes |
| | | 378 | | { |
| | 16 | 379 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 380 | | { |
| | 16 | 381 | | Log.Debug("Writing JSON response (async), StatusCode={StatusCode}, ContentType={ContentType}, Depth={Depth}, |
| | 16 | 382 | | statusCode, contentType, depth, compress); |
| | | 383 | | } |
| | | 384 | | |
| | 16 | 385 | | var serializerOptions = new JsonSerializerOptions |
| | 16 | 386 | | { |
| | 16 | 387 | | WriteIndented = !compress, |
| | 16 | 388 | | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 16 | 389 | | DictionaryKeyPolicy = JsonNamingPolicy.CamelCase, |
| | 16 | 390 | | ReferenceHandler = ReferenceHandler.IgnoreCycles, |
| | 16 | 391 | | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, |
| | 16 | 392 | | MaxDepth = depth |
| | 16 | 393 | | }; |
| | | 394 | | |
| | 16 | 395 | | await WriteJsonResponseAsync(inputObject, serializerOptions: serializerOptions, statusCode: statusCode, contentT |
| | 16 | 396 | | } |
| | | 397 | | /// <summary> |
| | | 398 | | /// Writes a CBOR response (binary, efficient, not human-readable). |
| | | 399 | | /// </summary> |
| | | 400 | | public async Task WriteCborResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? cont |
| | | 401 | | { |
| | 2 | 402 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 403 | | { |
| | 2 | 404 | | Log.Debug("Writing CBOR response, StatusCode={StatusCode}, ContentType={ContentType}", statusCode, contentTy |
| | | 405 | | } |
| | | 406 | | |
| | | 407 | | // Serialize to CBOR using PeterO.Cbor |
| | 4 | 408 | | Body = await Task.Run(() => inputObject != null |
| | 4 | 409 | | ? PeterO.Cbor.CBORObject.FromObject(inputObject).EncodeToBytes() |
| | 4 | 410 | | : []); |
| | 2 | 411 | | ContentType = string.IsNullOrEmpty(contentType) ? "application/cbor" : contentType; |
| | 2 | 412 | | StatusCode = statusCode; |
| | 2 | 413 | | } |
| | | 414 | | |
| | | 415 | | /// <summary> |
| | | 416 | | /// Writes a CBOR response (binary, efficient, not human-readable). |
| | | 417 | | /// </summary> |
| | | 418 | | /// <param name="inputObject">The object to be converted to CBOR.</param> |
| | | 419 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 420 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 0 | 421 | | public void WriteCborResponse(object? inputObject, int statusCode = StatusCodes.Status200OK, string? contentType = n |
| | | 422 | | |
| | | 423 | | /// <summary> |
| | | 424 | | /// Asynchronously writes a BSON response with the specified input object, status code, and content type. |
| | | 425 | | /// </summary> |
| | | 426 | | /// <param name="inputObject">The object to be converted to BSON.</param> |
| | | 427 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 428 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 429 | | public async Task WriteBsonResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? cont |
| | | 430 | | { |
| | 1 | 431 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 432 | | { |
| | 1 | 433 | | Log.Debug("Writing BSON response, StatusCode={StatusCode}, ContentType={ContentType}", statusCode, contentTy |
| | | 434 | | } |
| | | 435 | | |
| | | 436 | | // Serialize to BSON (as byte[]) |
| | 2 | 437 | | Body = await Task.Run(() => inputObject != null ? inputObject.ToBson() : []); |
| | 1 | 438 | | ContentType = string.IsNullOrEmpty(contentType) ? "application/bson" : contentType; |
| | 1 | 439 | | StatusCode = statusCode; |
| | 1 | 440 | | } |
| | | 441 | | |
| | | 442 | | /// <summary> |
| | | 443 | | /// Writes a BSON response with the specified input object, status code, and content type. |
| | | 444 | | /// </summary> |
| | | 445 | | /// <param name="inputObject">The object to be converted to BSON.</param> |
| | | 446 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 447 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 0 | 448 | | public void WriteBsonResponse(object? inputObject, int statusCode = StatusCodes.Status200OK, string? contentType = n |
| | | 449 | | |
| | | 450 | | /// <summary> |
| | | 451 | | /// Writes a response with the specified input object and HTTP status code. |
| | | 452 | | /// Chooses the response format based on the Accept header or defaults to text/plain. |
| | | 453 | | /// </summary> |
| | | 454 | | /// <param name="inputObject">The object to be sent in the response body.</param> |
| | | 455 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | 0 | 456 | | public void WriteResponse(object? inputObject, int statusCode = StatusCodes.Status200OK) => WriteResponseAsync(input |
| | | 457 | | |
| | | 458 | | /// <summary> |
| | | 459 | | /// Asynchronously writes a response with the specified input object and HTTP status code. |
| | | 460 | | /// Chooses the response format based on the Accept header or defaults to text/plain. |
| | | 461 | | /// </summary> |
| | | 462 | | /// <param name="inputObject">The object to be sent in the response body.</param> |
| | | 463 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 464 | | /// <returns>A task that represents the asynchronous write operation.</returns> |
| | | 465 | | public async Task WriteResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK) |
| | | 466 | | { |
| | 5 | 467 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 468 | | { |
| | 5 | 469 | | Log.Debug("Writing response, StatusCode={StatusCode}", statusCode); |
| | | 470 | | } |
| | | 471 | | |
| | 5 | 472 | | Body = inputObject; |
| | | 473 | | try |
| | | 474 | | { |
| | 5 | 475 | | string? acceptHeader = null; |
| | 5 | 476 | | _ = Request?.Headers.TryGetValue(HeaderNames.Accept, out acceptHeader); |
| | | 477 | | // Pick best media type from Accept, default to text/plain |
| | 5 | 478 | | var selected = SelectResponseMediaType(acceptHeader, defaultType: KrContext.MapRouteOptions.DefaultResponseC |
| | | 479 | | |
| | 5 | 480 | | if (selected is null) |
| | | 481 | | { |
| | 0 | 482 | | statusCode = StatusCodes.Status406NotAcceptable; |
| | 0 | 483 | | await WriteErrorResponseAsync("No acceptable media type found.", statusCode); |
| | 0 | 484 | | return; |
| | | 485 | | } |
| | | 486 | | |
| | 5 | 487 | | if (Log.IsEnabled(LogEventLevel.Verbose)) |
| | | 488 | | { |
| | 0 | 489 | | Log.Verbose("Selected response media type={MediaType}", selected); |
| | | 490 | | } |
| | | 491 | | |
| | | 492 | | // Dispatch based on selected media type |
| | 5 | 493 | | await WriteByMediaTypeAsync(selected, inputObject, statusCode); |
| | 5 | 494 | | } |
| | 0 | 495 | | catch (Exception ex) |
| | | 496 | | { |
| | 0 | 497 | | Log.Error("Error in WriteResponseAsync: {Message}", ex.Message); |
| | 0 | 498 | | await WriteErrorResponseAsync($"Internal server error: {ex.Message}", StatusCodes.Status500InternalServerErr |
| | | 499 | | } |
| | 5 | 500 | | } |
| | | 501 | | |
| | | 502 | | /// <summary> |
| | | 503 | | /// Selects the most appropriate response media type based on the Accept header. |
| | | 504 | | /// </summary> |
| | | 505 | | /// <param name="acceptHeader">The value of the Accept header from the request.</param> |
| | | 506 | | /// <param name="defaultType">The default media type to use if no match is found. Defaults to "text/plain".</param> |
| | | 507 | | /// <returns>The selected media type as a string.</returns> |
| | | 508 | | /// <remarks> |
| | | 509 | | /// This method parses the Accept header, orders the media types by quality factor, |
| | | 510 | | /// and selects the first supported media type. If none are supported, it returns the default type. |
| | | 511 | | /// </remarks> |
| | | 512 | | private static string? SelectResponseMediaType(string? acceptHeader, string? defaultType = "text/plain") |
| | | 513 | | { |
| | 5 | 514 | | if (string.IsNullOrWhiteSpace(acceptHeader)) |
| | | 515 | | { |
| | 0 | 516 | | return defaultType; |
| | | 517 | | } |
| | | 518 | | // Parse and order by quality factor (q=) |
| | 5 | 519 | | var acceptValues = MediaTypeHeaderValue |
| | 5 | 520 | | .ParseList(acceptHeader.Split(',')) |
| | 11 | 521 | | .OrderByDescending(v => v.Quality ?? 1.0); |
| | | 522 | | // Try to find a supported media type |
| | 15 | 523 | | foreach (var v in acceptValues) |
| | | 524 | | { |
| | 5 | 525 | | var mediaType = GetMediaTypeOrNull(v); |
| | 5 | 526 | | if (mediaType is not null) |
| | | 527 | | { |
| | | 528 | | // Map to canonical media type if needed |
| | 5 | 529 | | var mapped = MediaTypeHelper.Canonicalize(mediaType); |
| | 5 | 530 | | if (mapped is not null) |
| | | 531 | | { |
| | 5 | 532 | | return mapped; |
| | | 533 | | } |
| | | 534 | | } |
| | | 535 | | } |
| | | 536 | | // No supported media type found; return default |
| | 0 | 537 | | return defaultType; |
| | 5 | 538 | | } |
| | | 539 | | |
| | | 540 | | /// <summary> |
| | | 541 | | /// Gets the media type from the MediaTypeHeaderValue or null if not present. |
| | | 542 | | /// </summary> |
| | | 543 | | /// <param name="v"> The MediaTypeHeaderValue instance to extract the media type from.</param> |
| | | 544 | | /// <returns>The media type as a string if present; otherwise, null.</returns> |
| | | 545 | | private static string? GetMediaTypeOrNull(MediaTypeHeaderValue v) |
| | | 546 | | { |
| | 5 | 547 | | if (!v.MediaType.HasValue) |
| | | 548 | | { |
| | 0 | 549 | | return null; |
| | | 550 | | } |
| | | 551 | | // Trim whitespace |
| | 5 | 552 | | var s = v.MediaType.Value.Trim(); |
| | | 553 | | // Return null for empty strings |
| | 5 | 554 | | return s.Length == 0 ? null : s; |
| | | 555 | | } |
| | | 556 | | |
| | | 557 | | /// <summary> |
| | | 558 | | /// Writes a response based on the specified media type. |
| | | 559 | | /// </summary> |
| | | 560 | | /// <param name="mediaType">The media type to use for the response.</param> |
| | | 561 | | /// <param name="inputObject">The object to be written in the response body.</param> |
| | | 562 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 563 | | /// <returns>A Task representing the asynchronous operation.</returns> |
| | | 564 | | private Task WriteByMediaTypeAsync(string mediaType, object? inputObject, int statusCode) |
| | | 565 | | { |
| | | 566 | | // If you want, set Response.ContentType here once, centrally. |
| | 5 | 567 | | ContentType = mediaType; |
| | | 568 | | |
| | 5 | 569 | | return mediaType switch |
| | 5 | 570 | | { |
| | 3 | 571 | | "application/json" => WriteJsonResponseAsync(inputObject, statusCode, mediaType), |
| | 0 | 572 | | "application/yaml" => WriteYamlResponseAsync(inputObject, statusCode, mediaType), |
| | 0 | 573 | | "application/xml" => WriteXmlResponseAsync(inputObject, statusCode, mediaType), |
| | 0 | 574 | | "application/bson" => WriteBsonResponseAsync(inputObject, statusCode, mediaType), |
| | 0 | 575 | | "application/cbor" => WriteCborResponseAsync(inputObject, statusCode, mediaType), |
| | 1 | 576 | | "text/csv" => WriteCsvResponseAsync(inputObject, statusCode, mediaType), |
| | 0 | 577 | | "application/x-www-form-urlencoded" => WriteFormUrlEncodedResponseAsync(inputObject, statusCode), |
| | 1 | 578 | | _ => WriteTextResponseAsync(inputObject?.ToString() ?? string.Empty, statusCode), |
| | 5 | 579 | | }; |
| | | 580 | | } |
| | | 581 | | |
| | | 582 | | /// <summary> |
| | | 583 | | /// Writes a CSV response with the specified input object, status code, content type, and optional CsvConfiguration. |
| | | 584 | | /// </summary> |
| | | 585 | | /// <param name="inputObject">The object to be converted to CSV.</param> |
| | | 586 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 587 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 588 | | /// <param name="config">An optional CsvConfiguration to customize CSV output.</param> |
| | | 589 | | public void WriteCsvResponse( |
| | | 590 | | object? inputObject, |
| | | 591 | | int statusCode = StatusCodes.Status200OK, |
| | | 592 | | string? contentType = null, |
| | | 593 | | CsvConfiguration? config = null) |
| | | 594 | | { |
| | 2 | 595 | | Action<CsvConfiguration>? tweaker = null; |
| | | 596 | | |
| | 2 | 597 | | if (config is not null) |
| | | 598 | | { |
| | 1 | 599 | | tweaker = target => |
| | 1 | 600 | | { |
| | 90 | 601 | | foreach (var prop in typeof(CsvConfiguration) |
| | 1 | 602 | | .GetProperties(BindingFlags.Public | BindingFlags.Instance)) |
| | 1 | 603 | | { |
| | 44 | 604 | | if (prop.CanRead && prop.CanWrite) |
| | 1 | 605 | | { |
| | 44 | 606 | | var value = prop.GetValue(config); |
| | 44 | 607 | | prop.SetValue(target, value); |
| | 1 | 608 | | } |
| | 1 | 609 | | } |
| | 2 | 610 | | }; |
| | | 611 | | } |
| | 2 | 612 | | WriteCsvResponseAsync(inputObject, statusCode, contentType, tweaker).GetAwaiter().GetResult(); |
| | 2 | 613 | | } |
| | | 614 | | |
| | | 615 | | /// <summary> |
| | | 616 | | /// Asynchronously writes a CSV response with the specified input object, status code, content type, and optional co |
| | | 617 | | /// </summary> |
| | | 618 | | /// <param name="inputObject">The object to be converted to CSV.</param> |
| | | 619 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 620 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 621 | | /// <param name="tweak">An optional action to tweak the CsvConfiguration.</param> |
| | | 622 | | public async Task WriteCsvResponseAsync( |
| | | 623 | | object? inputObject, |
| | | 624 | | int statusCode = StatusCodes.Status200OK, |
| | | 625 | | string? contentType = null, |
| | | 626 | | Action<CsvConfiguration>? tweak = null) |
| | | 627 | | { |
| | 4 | 628 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 629 | | { |
| | 4 | 630 | | Log.Debug("Writing CSV response (async), StatusCode={StatusCode}, ContentType={ContentType}", |
| | 4 | 631 | | statusCode, contentType); |
| | | 632 | | } |
| | | 633 | | |
| | | 634 | | // Serialize inside a background task so heavy reflection never blocks the caller |
| | 4 | 635 | | Body = await Task.Run(() => |
| | 4 | 636 | | { |
| | 4 | 637 | | var cfg = new CsvConfiguration(CultureInfo.InvariantCulture) |
| | 4 | 638 | | { |
| | 4 | 639 | | HasHeaderRecord = true, |
| | 4 | 640 | | NewLine = Environment.NewLine |
| | 4 | 641 | | }; |
| | 4 | 642 | | tweak?.Invoke(cfg); // let the caller flirt with the config |
| | 4 | 643 | | |
| | 4 | 644 | | using var sw = new StringWriter(); |
| | 4 | 645 | | using var csv = new CsvWriter(sw, cfg); |
| | 4 | 646 | | |
| | 4 | 647 | | // CsvHelper insists on an enumerable; wrap single objects so it stays happy |
| | 4 | 648 | | if (inputObject is IEnumerable records and not string) |
| | 4 | 649 | | { |
| | 4 | 650 | | csv.WriteRecords(records); // whole collections (IEnumerable<T>) |
| | 4 | 651 | | } |
| | 0 | 652 | | else if (inputObject is not null) |
| | 4 | 653 | | { |
| | 0 | 654 | | csv.WriteRecords([inputObject]); // lone POCO |
| | 4 | 655 | | } |
| | 4 | 656 | | else |
| | 4 | 657 | | { |
| | 0 | 658 | | csv.WriteHeader<object>(); // nothing? write only headers for an empty file |
| | 4 | 659 | | } |
| | 4 | 660 | | |
| | 4 | 661 | | return sw.ToString(); |
| | 8 | 662 | | }).ConfigureAwait(false); |
| | | 663 | | |
| | 4 | 664 | | ContentType = string.IsNullOrEmpty(contentType) |
| | 4 | 665 | | ? $"text/csv; charset={Encoding.WebName}" |
| | 4 | 666 | | : contentType; |
| | 4 | 667 | | StatusCode = statusCode; |
| | 4 | 668 | | } |
| | | 669 | | /// <summary> |
| | | 670 | | /// Writes a YAML response with the specified input object, status code, and content type. |
| | | 671 | | /// </summary> |
| | | 672 | | /// <param name="inputObject">The object to be converted to YAML.</param> |
| | | 673 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 674 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | 1 | 675 | | public void WriteYamlResponse(object? inputObject, int statusCode = StatusCodes.Status200OK, string? contentType = n |
| | | 676 | | |
| | | 677 | | /// <summary> |
| | | 678 | | /// Asynchronously writes a YAML response with the specified input object, status code, and content type. |
| | | 679 | | /// </summary> |
| | | 680 | | /// <param name="inputObject">The object to be converted to YAML.</param> |
| | | 681 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 682 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 683 | | public async Task WriteYamlResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? cont |
| | | 684 | | { |
| | 3 | 685 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 686 | | { |
| | 3 | 687 | | Log.Debug("Writing YAML response (async), StatusCode={StatusCode}, ContentType={ContentType}", statusCode, c |
| | | 688 | | } |
| | | 689 | | |
| | 6 | 690 | | Body = await Task.Run(() => YamlHelper.ToYaml(inputObject)); |
| | 3 | 691 | | ContentType = string.IsNullOrEmpty(contentType) ? $"application/yaml; charset={Encoding.WebName}" : contentType; |
| | 3 | 692 | | StatusCode = statusCode; |
| | 3 | 693 | | } |
| | | 694 | | |
| | | 695 | | /// <summary> |
| | | 696 | | /// Writes an XML response with the specified input object, status code, and content type. |
| | | 697 | | /// </summary> |
| | | 698 | | /// <param name="inputObject">The object to be converted to XML.</param> |
| | | 699 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 700 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 701 | | /// <param name="rootElementName">Optional custom XML root element name. Defaults to <c>Response</c>.</param> |
| | | 702 | | /// <param name="compress">If true, emits compact XML (no indentation); if false (default) output is human readable. |
| | | 703 | | public void WriteXmlResponse(object? inputObject, int statusCode = StatusCodes.Status200OK, string? contentType = nu |
| | 6 | 704 | | => WriteXmlResponseAsync(inputObject, statusCode, contentType, rootElementName, compress).GetAwaiter().GetResult |
| | | 705 | | |
| | | 706 | | /// <summary> |
| | | 707 | | /// Asynchronously writes an XML response with the specified input object, status code, and content type. |
| | | 708 | | /// </summary> |
| | | 709 | | /// <param name="inputObject">The object to be converted to XML.</param> |
| | | 710 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 711 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 712 | | /// <param name="rootElementName">Optional custom XML root element name. Defaults to <c>Response</c>.</param> |
| | | 713 | | /// <param name="compress">If true, emits compact XML (no indentation); if false (default) output is human readable. |
| | | 714 | | public async Task WriteXmlResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? conte |
| | | 715 | | { |
| | 8 | 716 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 717 | | { |
| | 8 | 718 | | Log.Debug("Writing XML response (async), StatusCode={StatusCode}, ContentType={ContentType}", statusCode, co |
| | | 719 | | } |
| | | 720 | | |
| | 8 | 721 | | var root = string.IsNullOrWhiteSpace(rootElementName) ? "Response" : rootElementName.Trim(); |
| | 16 | 722 | | var xml = await Task.Run(() => XmlHelper.ToXml(root, inputObject)); |
| | 8 | 723 | | var saveOptions = compress ? SaveOptions.DisableFormatting : SaveOptions.None; |
| | 16 | 724 | | Body = await Task.Run(() => xml.ToString(saveOptions)); |
| | 8 | 725 | | ContentType = string.IsNullOrEmpty(contentType) ? $"application/xml; charset={Encoding.WebName}" : contentType; |
| | 8 | 726 | | StatusCode = statusCode; |
| | 8 | 727 | | } |
| | | 728 | | /// <summary> |
| | | 729 | | /// Writes a text response with the specified input object, status code, and content type. |
| | | 730 | | /// </summary> |
| | | 731 | | /// <param name="inputObject">The object to be converted to a text response.</param> |
| | | 732 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 733 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 734 | | public void WriteTextResponse(object? inputObject, int statusCode = StatusCodes.Status200OK, string? contentType = n |
| | 8 | 735 | | WriteTextResponseAsync(inputObject, statusCode, contentType).GetAwaiter().GetResult(); |
| | | 736 | | |
| | | 737 | | /// <summary> |
| | | 738 | | /// Asynchronously writes a text response with the specified input object, status code, and content type. |
| | | 739 | | /// </summary> |
| | | 740 | | /// <param name="inputObject">The object to be converted to a text response.</param> |
| | | 741 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 742 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 743 | | public async Task WriteTextResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK, string? cont |
| | | 744 | | { |
| | 35 | 745 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 746 | | { |
| | 34 | 747 | | Log.Debug("Writing text response (async), StatusCode={StatusCode}, ContentType={ContentType}", statusCode, c |
| | | 748 | | } |
| | | 749 | | |
| | 35 | 750 | | if (inputObject is null) |
| | | 751 | | { |
| | 0 | 752 | | throw new ArgumentNullException(nameof(inputObject), "Input object cannot be null for text response."); |
| | | 753 | | } |
| | | 754 | | |
| | 70 | 755 | | Body = await Task.Run(() => inputObject?.ToString() ?? string.Empty); |
| | 35 | 756 | | ContentType = string.IsNullOrEmpty(contentType) ? $"text/plain; charset={Encoding.WebName}" : contentType; |
| | 35 | 757 | | StatusCode = statusCode; |
| | 35 | 758 | | } |
| | | 759 | | |
| | | 760 | | /// <summary> |
| | | 761 | | /// Writes a form-urlencoded response with the specified input object, status code, and optional content type. |
| | | 762 | | /// Automatically converts the input object to a Dictionary{string, string} using <see cref="ObjectToDictionaryConve |
| | | 763 | | /// </summary> |
| | | 764 | | /// <param name="inputObject">The object to be converted to form-urlencoded data. Can be a dictionary, enumerable, o |
| | | 765 | | /// <param name="statusCode">The HTTP status code for the response. Defaults to 200 OK.</param> |
| | | 766 | | public void WriteFormUrlEncodedResponse(object? inputObject, int statusCode = StatusCodes.Status200OK) => |
| | 8 | 767 | | WriteFormUrlEncodedResponseAsync(inputObject, statusCode).GetAwaiter().GetResult(); |
| | | 768 | | |
| | | 769 | | /// <summary> |
| | | 770 | | /// Asynchronously writes a form-urlencoded response with the specified input object, status code, and optional cont |
| | | 771 | | /// Automatically converts the input object to a Dictionary{string, string} using <see cref="ObjectToDictionaryConve |
| | | 772 | | /// </summary> |
| | | 773 | | /// <param name="inputObject">The object to be converted to form-urlencoded data. Can be a dictionary, enumerable, o |
| | | 774 | | /// <param name="statusCode">The HTTP status code for the response. Defaults to 200 OK.</param> |
| | | 775 | | public async Task WriteFormUrlEncodedResponseAsync(object? inputObject, int statusCode = StatusCodes.Status200OK) |
| | | 776 | | { |
| | 11 | 777 | | if (inputObject is null) |
| | | 778 | | { |
| | 2 | 779 | | throw new ArgumentNullException(nameof(inputObject), "Input object cannot be null for form-urlencoded respon |
| | | 780 | | } |
| | | 781 | | |
| | 9 | 782 | | var dictionary = ObjectToDictionaryConverter.ToDictionary(inputObject); |
| | 9 | 783 | | var formContent = new FormUrlEncodedContent(dictionary); |
| | 9 | 784 | | var encodedString = await formContent.ReadAsStringAsync(); |
| | | 785 | | |
| | 9 | 786 | | await WriteTextResponseAsync(encodedString, statusCode, "application/x-www-form-urlencoded"); |
| | 9 | 787 | | } |
| | | 788 | | |
| | | 789 | | /// <summary> |
| | | 790 | | /// Writes an HTTP redirect response with the specified URL and optional message. |
| | | 791 | | /// </summary> |
| | | 792 | | /// <param name="url">The URL to redirect to.</param> |
| | | 793 | | /// <param name="message">An optional message to include in the response body.</param> |
| | | 794 | | public void WriteRedirectResponse(string url, string? message = null) |
| | | 795 | | { |
| | 6 | 796 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 797 | | { |
| | 5 | 798 | | Log.Debug("Writing redirect response, StatusCode={StatusCode}, Location={Location}", StatusCode, url); |
| | | 799 | | } |
| | | 800 | | |
| | 6 | 801 | | if (string.IsNullOrEmpty(url)) |
| | | 802 | | { |
| | 0 | 803 | | throw new ArgumentNullException(nameof(url), "URL cannot be null for redirect response."); |
| | | 804 | | } |
| | | 805 | | // framework hook |
| | 6 | 806 | | RedirectUrl = url; |
| | | 807 | | |
| | | 808 | | // HTTP status + Location header |
| | 6 | 809 | | StatusCode = StatusCodes.Status302Found; |
| | 6 | 810 | | Headers["Location"] = url; |
| | | 811 | | |
| | 6 | 812 | | if (message is not null) |
| | | 813 | | { |
| | | 814 | | // include a body |
| | 1 | 815 | | Body = message; |
| | 1 | 816 | | ContentType = $"text/plain; charset={Encoding.WebName}"; |
| | | 817 | | } |
| | | 818 | | else |
| | | 819 | | { |
| | | 820 | | // no body: clear any existing body/headers |
| | 5 | 821 | | Body = null; |
| | | 822 | | //ContentType = null; |
| | 5 | 823 | | _ = Headers.Remove("Content-Length"); |
| | | 824 | | } |
| | 5 | 825 | | } |
| | | 826 | | |
| | | 827 | | /// <summary> |
| | | 828 | | /// Writes a binary response with the specified data, status code, and content type. |
| | | 829 | | /// </summary> |
| | | 830 | | /// <param name="data">The binary data to send in the response.</param> |
| | | 831 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 832 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 833 | | public void WriteBinaryResponse(byte[] data, int statusCode = StatusCodes.Status200OK, string contentType = "applica |
| | | 834 | | { |
| | 1 | 835 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 836 | | { |
| | 1 | 837 | | Log.Debug("Writing binary response, StatusCode={StatusCode}, ContentType={ContentType}", statusCode, content |
| | | 838 | | } |
| | | 839 | | |
| | 1 | 840 | | Body = data ?? throw new ArgumentNullException(nameof(data), "Data cannot be null for binary response."); |
| | 1 | 841 | | ContentType = contentType; |
| | 1 | 842 | | StatusCode = statusCode; |
| | 1 | 843 | | } |
| | | 844 | | /// <summary> |
| | | 845 | | /// Writes a stream response with the specified stream, status code, and content type. |
| | | 846 | | /// </summary> |
| | | 847 | | /// <param name="stream">The stream to send in the response.</param> |
| | | 848 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 849 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 850 | | public void WriteStreamResponse(Stream stream, int statusCode = StatusCodes.Status200OK, string contentType = "appli |
| | | 851 | | { |
| | 3 | 852 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 853 | | { |
| | 3 | 854 | | Log.Debug("Writing stream response, StatusCode={StatusCode}, ContentType={ContentType}", statusCode, content |
| | | 855 | | } |
| | | 856 | | |
| | 3 | 857 | | Body = stream; |
| | 3 | 858 | | ContentType = contentType; |
| | 3 | 859 | | StatusCode = statusCode; |
| | 3 | 860 | | } |
| | | 861 | | #endregion |
| | | 862 | | |
| | | 863 | | #region Error Responses |
| | | 864 | | /// <summary> |
| | | 865 | | /// Structured payload for error responses. |
| | | 866 | | /// </summary> |
| | | 867 | | internal record ErrorPayload |
| | | 868 | | { |
| | 26 | 869 | | public string Error { get; init; } = default!; |
| | 27 | 870 | | public string? Details { get; init; } |
| | 29 | 871 | | public string? Exception { get; init; } |
| | 28 | 872 | | public string? StackTrace { get; init; } |
| | 52 | 873 | | public int Status { get; init; } |
| | 26 | 874 | | public string Reason { get; init; } = default!; |
| | 26 | 875 | | public string Timestamp { get; init; } = default!; |
| | 20 | 876 | | public string? Path { get; init; } |
| | 20 | 877 | | public string? Method { get; init; } |
| | | 878 | | } |
| | | 879 | | |
| | | 880 | | /// <summary> |
| | | 881 | | /// Write an error response with a custom message. |
| | | 882 | | /// Chooses JSON/YAML/XML/plain-text based on override → Accept → default JSON. |
| | | 883 | | /// </summary> |
| | | 884 | | public async Task WriteErrorResponseAsync( |
| | | 885 | | string message, |
| | | 886 | | int statusCode = StatusCodes.Status500InternalServerError, |
| | | 887 | | string? contentType = null, |
| | | 888 | | string? details = null) |
| | | 889 | | { |
| | 10 | 890 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 891 | | { |
| | 10 | 892 | | Log.Debug("Writing error response, StatusCode={StatusCode}, ContentType={ContentType}, Message={Message}", |
| | 10 | 893 | | statusCode, contentType, message); |
| | | 894 | | } |
| | | 895 | | |
| | 10 | 896 | | if (string.IsNullOrWhiteSpace(message)) |
| | | 897 | | { |
| | 0 | 898 | | throw new ArgumentNullException(nameof(message)); |
| | | 899 | | } |
| | | 900 | | |
| | 10 | 901 | | Log.Warning("Writing error response with status {StatusCode}: {Message}", statusCode, message); |
| | | 902 | | |
| | 10 | 903 | | var payload = new ErrorPayload |
| | 10 | 904 | | { |
| | 10 | 905 | | Error = message, |
| | 10 | 906 | | Details = details, |
| | 10 | 907 | | Exception = null, |
| | 10 | 908 | | StackTrace = null, |
| | 10 | 909 | | Status = statusCode, |
| | 10 | 910 | | Reason = ReasonPhrases.GetReasonPhrase(statusCode), |
| | 10 | 911 | | Timestamp = DateTime.UtcNow.ToString("o"), |
| | 10 | 912 | | Path = Request?.Path, |
| | 10 | 913 | | Method = Request?.Method |
| | 10 | 914 | | }; |
| | | 915 | | |
| | 10 | 916 | | await WriteFormattedErrorResponseAsync(payload, contentType); |
| | 10 | 917 | | } |
| | | 918 | | |
| | | 919 | | /// <summary> |
| | | 920 | | /// Writes an error response with a custom message. |
| | | 921 | | /// Chooses JSON/YAML/XML/plain-text based on override → Accept → default JSON. |
| | | 922 | | /// </summary> |
| | | 923 | | /// <param name="message">The error message to include in the response.</param> |
| | | 924 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 925 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 926 | | /// <param name="details">Optional details to include in the response.</param> |
| | | 927 | | public void WriteErrorResponse( |
| | | 928 | | string message, |
| | | 929 | | int statusCode = StatusCodes.Status500InternalServerError, |
| | | 930 | | string? contentType = null, |
| | 1 | 931 | | string? details = null) => WriteErrorResponseAsync(message, statusCode, contentType, details).GetAwaiter().GetResu |
| | | 932 | | |
| | | 933 | | /// <summary> |
| | | 934 | | /// Asynchronously writes an error response based on an exception. |
| | | 935 | | /// Chooses JSON/YAML/XML/plain-text based on override → Accept → default JSON. |
| | | 936 | | /// </summary> |
| | | 937 | | /// <param name="ex">The exception to report.</param> |
| | | 938 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 939 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 940 | | /// <param name="includeStack">Whether to include the stack trace in the response.</param> |
| | | 941 | | public async Task WriteErrorResponseAsync( |
| | | 942 | | Exception ex, |
| | | 943 | | int statusCode = StatusCodes.Status500InternalServerError, |
| | | 944 | | string? contentType = null, |
| | | 945 | | bool includeStack = true) |
| | | 946 | | { |
| | 3 | 947 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 948 | | { |
| | 3 | 949 | | Log.Debug("Writing error response from exception, StatusCode={StatusCode}, ContentType={ContentType}, Includ |
| | 3 | 950 | | statusCode, contentType, includeStack); |
| | | 951 | | } |
| | | 952 | | |
| | 3 | 953 | | ArgumentNullException.ThrowIfNull(ex); |
| | | 954 | | |
| | 3 | 955 | | Log.Warning(ex, "Writing error response with status {StatusCode}", statusCode); |
| | | 956 | | |
| | 3 | 957 | | var payload = new ErrorPayload |
| | 3 | 958 | | { |
| | 3 | 959 | | Error = ex.Message, |
| | 3 | 960 | | Details = null, |
| | 3 | 961 | | Exception = ex.GetType().Name, |
| | 3 | 962 | | StackTrace = includeStack ? ex.ToString() : null, |
| | 3 | 963 | | Status = statusCode, |
| | 3 | 964 | | Reason = ReasonPhrases.GetReasonPhrase(statusCode), |
| | 3 | 965 | | Timestamp = DateTime.UtcNow.ToString("o"), |
| | 3 | 966 | | Path = Request?.Path, |
| | 3 | 967 | | Method = Request?.Method |
| | 3 | 968 | | }; |
| | | 969 | | |
| | 3 | 970 | | await WriteFormattedErrorResponseAsync(payload, contentType); |
| | 3 | 971 | | } |
| | | 972 | | /// <summary> |
| | | 973 | | /// Writes an error response based on an exception. |
| | | 974 | | /// Chooses JSON/YAML/XML/plain-text based on override → Accept → default JSON. |
| | | 975 | | /// </summary> |
| | | 976 | | /// <param name="ex">The exception to report.</param> |
| | | 977 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 978 | | /// <param name="contentType">The MIME type of the response content.</param> |
| | | 979 | | /// <param name="includeStack">Whether to include the stack trace in the response.</param> |
| | | 980 | | public void WriteErrorResponse( |
| | | 981 | | Exception ex, |
| | | 982 | | int statusCode = StatusCodes.Status500InternalServerError, |
| | | 983 | | string? contentType = null, |
| | 1 | 984 | | bool includeStack = true) => WriteErrorResponseAsync(ex, statusCode, contentType, includeStack).GetAwaiter() |
| | | 985 | | |
| | | 986 | | /// <summary> |
| | | 987 | | /// Internal dispatcher: serializes the payload according to the chosen content-type. |
| | | 988 | | /// </summary> |
| | | 989 | | private async Task WriteFormattedErrorResponseAsync(ErrorPayload payload, string? contentType = null) |
| | | 990 | | { |
| | 13 | 991 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 992 | | { |
| | 13 | 993 | | Log.Debug("Writing formatted error response, ContentType={ContentType}, Status={Status}", contentType, paylo |
| | | 994 | | } |
| | | 995 | | |
| | 13 | 996 | | if (string.IsNullOrWhiteSpace(contentType)) |
| | | 997 | | { |
| | 11 | 998 | | _ = Request.Headers.TryGetValue("Accept", out var acceptHeader); |
| | 11 | 999 | | contentType = (acceptHeader ?? "text/plain") |
| | 11 | 1000 | | .ToLowerInvariant(); |
| | | 1001 | | } |
| | 13 | 1002 | | if (contentType.Contains("json")) |
| | | 1003 | | { |
| | 3 | 1004 | | await WriteJsonResponseAsync(payload, payload.Status); |
| | | 1005 | | } |
| | 10 | 1006 | | else if (contentType.Contains("yaml") || contentType.Contains("yml")) |
| | | 1007 | | { |
| | 2 | 1008 | | await WriteYamlResponseAsync(payload, payload.Status); |
| | | 1009 | | } |
| | 8 | 1010 | | else if (contentType.Contains("xml")) |
| | | 1011 | | { |
| | 2 | 1012 | | await WriteXmlResponseAsync(payload, payload.Status); |
| | | 1013 | | } |
| | | 1014 | | else |
| | | 1015 | | { |
| | | 1016 | | // Plain-text fallback |
| | 6 | 1017 | | var lines = new List<string> |
| | 6 | 1018 | | { |
| | 6 | 1019 | | $"Status: {payload.Status} ({payload.Reason})", |
| | 6 | 1020 | | $"Error: {payload.Error}", |
| | 6 | 1021 | | $"Time: {payload.Timestamp}" |
| | 6 | 1022 | | }; |
| | | 1023 | | |
| | 6 | 1024 | | if (!string.IsNullOrWhiteSpace(payload.Details)) |
| | | 1025 | | { |
| | 1 | 1026 | | lines.Add("Details:\n" + payload.Details); |
| | | 1027 | | } |
| | | 1028 | | |
| | 6 | 1029 | | if (!string.IsNullOrWhiteSpace(payload.Exception)) |
| | | 1030 | | { |
| | 3 | 1031 | | lines.Add($"Exception: {payload.Exception}"); |
| | | 1032 | | } |
| | | 1033 | | |
| | 6 | 1034 | | if (!string.IsNullOrWhiteSpace(payload.StackTrace)) |
| | | 1035 | | { |
| | 2 | 1036 | | lines.Add("StackTrace:\n" + payload.StackTrace); |
| | | 1037 | | } |
| | | 1038 | | |
| | 6 | 1039 | | var text = string.Join("\n", lines); |
| | 6 | 1040 | | await WriteTextResponseAsync(text, payload.Status, "text/plain"); |
| | | 1041 | | } |
| | 13 | 1042 | | } |
| | | 1043 | | |
| | | 1044 | | #endregion |
| | | 1045 | | #region HTML Response Helpers |
| | | 1046 | | |
| | | 1047 | | /// <summary> |
| | | 1048 | | /// Renders a template string by replacing placeholders in the format {{key}} with corresponding values from the pro |
| | | 1049 | | /// </summary> |
| | | 1050 | | /// <param name="template">The template string containing placeholders.</param> |
| | | 1051 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 1052 | | /// <returns>The rendered string with placeholders replaced by variable values.</returns> |
| | | 1053 | | private static string RenderInlineTemplate( |
| | | 1054 | | string template, |
| | | 1055 | | IReadOnlyDictionary<string, object?> vars) |
| | | 1056 | | { |
| | 2 | 1057 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 1058 | | { |
| | 2 | 1059 | | Log.Debug("Rendering inline template, TemplateLength={TemplateLength}, VarsCount={VarsCount}", |
| | 2 | 1060 | | template?.Length ?? 0, vars?.Count ?? 0); |
| | | 1061 | | } |
| | | 1062 | | |
| | 2 | 1063 | | if (string.IsNullOrEmpty(template)) |
| | | 1064 | | { |
| | 0 | 1065 | | return string.Empty; |
| | | 1066 | | } |
| | | 1067 | | |
| | 2 | 1068 | | if (vars is null || vars.Count == 0) |
| | | 1069 | | { |
| | 0 | 1070 | | return template; |
| | | 1071 | | } |
| | | 1072 | | |
| | 2 | 1073 | | var render = RenderInline(template, vars); |
| | | 1074 | | |
| | 2 | 1075 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 1076 | | { |
| | 2 | 1077 | | Log.Debug("Rendered template length: {RenderedLength}", render.Length); |
| | | 1078 | | } |
| | | 1079 | | |
| | 2 | 1080 | | return render; |
| | | 1081 | | } |
| | | 1082 | | |
| | | 1083 | | /// <summary> |
| | | 1084 | | /// Renders a template string by replacing placeholders in the format {{key}} with corresponding values from the pro |
| | | 1085 | | /// </summary> |
| | | 1086 | | /// <param name="template">The template string containing placeholders.</param> |
| | | 1087 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 1088 | | /// <returns>The rendered string with placeholders replaced by variable values.</returns> |
| | | 1089 | | private static string RenderInline(string template, IReadOnlyDictionary<string, object?> vars) |
| | | 1090 | | { |
| | 2 | 1091 | | var sb = new StringBuilder(template.Length); |
| | | 1092 | | |
| | | 1093 | | // Iterate through the template |
| | 2 | 1094 | | var i = 0; |
| | 39 | 1095 | | while (i < template.Length) |
| | | 1096 | | { |
| | | 1097 | | // opening “{{” |
| | 37 | 1098 | | if (template[i] == '{' && i + 1 < template.Length && template[i + 1] == '{') |
| | | 1099 | | { |
| | 3 | 1100 | | var start = i + 2; // after “{{” |
| | 3 | 1101 | | var end = template.IndexOf("}}", start, StringComparison.Ordinal); |
| | | 1102 | | |
| | 3 | 1103 | | if (end > start) // found closing “}}” |
| | | 1104 | | { |
| | 3 | 1105 | | var rawKey = template[start..end].Trim(); |
| | | 1106 | | |
| | 3 | 1107 | | if (TryResolveValue(rawKey, vars, out var value) && value is not null) |
| | | 1108 | | { |
| | 3 | 1109 | | _ = sb.Append(value); // append resolved value |
| | | 1110 | | } |
| | | 1111 | | else |
| | | 1112 | | { |
| | 0 | 1113 | | _ = sb.Append("{{").Append(rawKey).Append("}}"); // leave it as-is if unknown |
| | | 1114 | | } |
| | | 1115 | | |
| | 3 | 1116 | | i = end + 2; // jump past the “}}” |
| | 3 | 1117 | | continue; |
| | | 1118 | | } |
| | | 1119 | | } |
| | | 1120 | | |
| | | 1121 | | // ordinary character |
| | 34 | 1122 | | _ = sb.Append(template[i]); |
| | 34 | 1123 | | i++; // move to the next character |
| | | 1124 | | } |
| | 2 | 1125 | | return sb.ToString(); |
| | | 1126 | | } |
| | | 1127 | | |
| | | 1128 | | /// <summary> |
| | | 1129 | | /// Resolves a dotted path like “Request.Path” through nested dictionaries |
| | | 1130 | | /// and/or object properties (case-insensitive). |
| | | 1131 | | /// </summary> |
| | | 1132 | | private static bool TryResolveValue( |
| | | 1133 | | string path, |
| | | 1134 | | IReadOnlyDictionary<string, object?> root, |
| | | 1135 | | out object? value) |
| | | 1136 | | { |
| | 3 | 1137 | | value = null; |
| | | 1138 | | |
| | 3 | 1139 | | if (string.IsNullOrWhiteSpace(path)) |
| | | 1140 | | { |
| | 0 | 1141 | | return false; |
| | | 1142 | | } |
| | | 1143 | | |
| | 3 | 1144 | | object? current = root; |
| | 16 | 1145 | | foreach (var segment in path.Split('.')) |
| | | 1146 | | { |
| | 5 | 1147 | | if (current is null) |
| | | 1148 | | { |
| | 0 | 1149 | | return false; |
| | | 1150 | | } |
| | | 1151 | | |
| | | 1152 | | // ① Handle dictionary look-ups (IReadOnlyDictionary or IDictionary) |
| | 5 | 1153 | | if (current is IReadOnlyDictionary<string, object?> roDict) |
| | | 1154 | | { |
| | 3 | 1155 | | if (!roDict.TryGetValue(segment, out current)) |
| | | 1156 | | { |
| | 0 | 1157 | | return false; |
| | | 1158 | | } |
| | | 1159 | | |
| | | 1160 | | continue; |
| | | 1161 | | } |
| | | 1162 | | |
| | 2 | 1163 | | if (current is IDictionary dict) |
| | | 1164 | | { |
| | 0 | 1165 | | if (!dict.Contains(segment)) |
| | | 1166 | | { |
| | 0 | 1167 | | return false; |
| | | 1168 | | } |
| | | 1169 | | |
| | 0 | 1170 | | current = dict[segment]; |
| | 0 | 1171 | | continue; |
| | | 1172 | | } |
| | | 1173 | | |
| | | 1174 | | // ② Handle property look-ups via reflection |
| | 2 | 1175 | | var prop = current.GetType().GetProperty( |
| | 2 | 1176 | | segment, |
| | 2 | 1177 | | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); |
| | | 1178 | | |
| | 2 | 1179 | | if (prop is null) |
| | | 1180 | | { |
| | 0 | 1181 | | return false; |
| | | 1182 | | } |
| | | 1183 | | |
| | 2 | 1184 | | current = prop.GetValue(current); |
| | | 1185 | | } |
| | | 1186 | | |
| | 3 | 1187 | | value = current; |
| | 3 | 1188 | | return true; |
| | | 1189 | | } |
| | | 1190 | | |
| | | 1191 | | /// <summary> |
| | | 1192 | | /// Attempts to revalidate the cache based on ETag and Last-Modified headers. |
| | | 1193 | | /// If the resource is unchanged, sets the response status to 304 Not Modified. |
| | | 1194 | | /// Returns true if a 304 response was written, false otherwise. |
| | | 1195 | | /// </summary> |
| | | 1196 | | /// <param name="payload">The payload to validate.</param> |
| | | 1197 | | /// <param name="etag">The ETag header value.</param> |
| | | 1198 | | /// <param name="weakETag">Indicates if the ETag is a weak ETag.</param> |
| | | 1199 | | /// <param name="lastModified">The Last-Modified header value.</param> |
| | | 1200 | | /// <returns>True if a 304 response was written, false otherwise.</returns> |
| | | 1201 | | public bool RevalidateCache(object? payload, |
| | | 1202 | | string? etag = null, |
| | | 1203 | | bool weakETag = false, |
| | 0 | 1204 | | DateTimeOffset? lastModified = null) => CacheRevalidation.TryWrite304(Context, payload, etag, weakETag, lastModif |
| | | 1205 | | |
| | | 1206 | | /// <summary> |
| | | 1207 | | /// Asynchronously writes an HTML response, rendering the provided template string and replacing placeholders with v |
| | | 1208 | | /// </summary> |
| | | 1209 | | /// <param name="template">The HTML template string containing placeholders.</param> |
| | | 1210 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 1211 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1212 | | public async Task WriteHtmlResponseAsync( |
| | | 1213 | | string template, |
| | | 1214 | | IReadOnlyDictionary<string, object?>? vars, |
| | | 1215 | | int statusCode = 200) |
| | | 1216 | | { |
| | 2 | 1217 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 1218 | | { |
| | 2 | 1219 | | Log.Debug("Writing HTML response (async), StatusCode={StatusCode}, TemplateLength={TemplateLength}", statusC |
| | | 1220 | | } |
| | | 1221 | | |
| | 2 | 1222 | | if (vars is null || vars.Count == 0) |
| | | 1223 | | { |
| | 0 | 1224 | | await WriteTextResponseAsync(template, statusCode, "text/html"); |
| | | 1225 | | } |
| | | 1226 | | else |
| | | 1227 | | { |
| | 2 | 1228 | | await WriteTextResponseAsync(RenderInlineTemplate(template, vars), statusCode, "text/html"); |
| | | 1229 | | } |
| | 2 | 1230 | | } |
| | | 1231 | | |
| | | 1232 | | /// <summary> |
| | | 1233 | | /// Asynchronously writes an HTML response, rendering the provided template byte array and replacing placeholders wi |
| | | 1234 | | /// </summary> |
| | | 1235 | | /// <param name="template">The HTML template byte array.</param> |
| | | 1236 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 1237 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1238 | | /// <returns>A task representing the asynchronous operation.</returns> |
| | | 1239 | | public async Task WriteHtmlResponseAsync( |
| | | 1240 | | byte[] template, |
| | | 1241 | | IReadOnlyDictionary<string, object?>? vars, |
| | 0 | 1242 | | int statusCode = 200) => await WriteHtmlResponseAsync(Encoding.GetString(template), vars, statusCode); |
| | | 1243 | | |
| | | 1244 | | /// <summary> |
| | | 1245 | | /// Writes an HTML response, rendering the provided template byte array and replacing placeholders with values from |
| | | 1246 | | /// </summary> |
| | | 1247 | | /// <param name="template">The HTML template byte array.</param> |
| | | 1248 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 1249 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1250 | | public void WriteHtmlResponse( |
| | | 1251 | | byte[] template, |
| | | 1252 | | IReadOnlyDictionary<string, object?>? vars, |
| | 0 | 1253 | | int statusCode = 200) => WriteHtmlResponseAsync(Encoding.GetString(template), vars, statusCode).GetAwaiter().Ge |
| | | 1254 | | |
| | | 1255 | | /// <summary> |
| | | 1256 | | /// Asynchronously reads an HTML file, merges in placeholders from the provided dictionary, and writes the result as |
| | | 1257 | | /// </summary> |
| | | 1258 | | /// <param name="filePath">The path to the HTML file to read.</param> |
| | | 1259 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 1260 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1261 | | public async Task WriteHtmlResponseFromFileAsync( |
| | | 1262 | | string filePath, |
| | | 1263 | | IReadOnlyDictionary<string, object?> vars, |
| | | 1264 | | int statusCode = 200) |
| | | 1265 | | { |
| | 1 | 1266 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 1267 | | { |
| | 1 | 1268 | | Log.Debug("Writing HTML response from file (async), FilePath={FilePath}, StatusCode={StatusCode}", filePath, |
| | | 1269 | | } |
| | | 1270 | | |
| | 1 | 1271 | | if (!File.Exists(filePath)) |
| | | 1272 | | { |
| | 0 | 1273 | | WriteTextResponse($"<!-- File not found: {filePath} -->", 404, "text/html"); |
| | 0 | 1274 | | return; |
| | | 1275 | | } |
| | | 1276 | | |
| | 1 | 1277 | | var template = await File.ReadAllTextAsync(filePath); |
| | 1 | 1278 | | WriteHtmlResponseAsync(template, vars, statusCode).GetAwaiter().GetResult(); |
| | 1 | 1279 | | } |
| | | 1280 | | |
| | | 1281 | | /// <summary> |
| | | 1282 | | /// Renders the given HTML string with placeholders and writes it as a response. |
| | | 1283 | | /// </summary> |
| | | 1284 | | /// <param name="template">The HTML template string containing placeholders.</param> |
| | | 1285 | | /// <param name="vars">A dictionary of variables to replace in the template.</param> |
| | | 1286 | | /// <param name="statusCode">The HTTP status code for the response.</param> |
| | | 1287 | | public void WriteHtmlResponse( |
| | | 1288 | | string template, |
| | | 1289 | | IReadOnlyDictionary<string, object?>? vars, |
| | 0 | 1290 | | int statusCode = 200) => WriteHtmlResponseAsync(template, vars, statusCode).GetAwaiter().GetResult(); |
| | | 1291 | | |
| | | 1292 | | /// <summary> |
| | | 1293 | | /// Reads an .html file, merges in placeholders, and writes it. |
| | | 1294 | | /// </summary> |
| | | 1295 | | public void WriteHtmlResponseFromFile( |
| | | 1296 | | string filePath, |
| | | 1297 | | IReadOnlyDictionary<string, object?> vars, |
| | 0 | 1298 | | int statusCode = 200) => WriteHtmlResponseFromFileAsync(filePath, vars, statusCode).GetAwaiter().GetResult(); |
| | | 1299 | | |
| | | 1300 | | /// <summary> |
| | | 1301 | | /// Writes only the specified HTTP status code, clearing any body or content type. |
| | | 1302 | | /// </summary> |
| | | 1303 | | /// <param name="statusCode">The HTTP status code to write.</param> |
| | | 1304 | | public void WriteStatusOnly(int statusCode) |
| | | 1305 | | { |
| | | 1306 | | // Clear any body indicators so StatusCodePages can run |
| | 1 | 1307 | | ContentType = null; |
| | 1 | 1308 | | StatusCode = statusCode; |
| | 1 | 1309 | | Body = null; |
| | 1 | 1310 | | } |
| | | 1311 | | #endregion |
| | | 1312 | | |
| | | 1313 | | #region Apply to HttpResponse |
| | | 1314 | | |
| | | 1315 | | /// <summary> |
| | | 1316 | | /// Applies the current KestrunResponse to the specified HttpResponse, setting status, headers, cookies, and writing |
| | | 1317 | | /// </summary> |
| | | 1318 | | /// <param name="response">The HttpResponse to apply the response to.</param> |
| | | 1319 | | /// <returns>A task representing the asynchronous operation.</returns> |
| | | 1320 | | public async Task ApplyTo(HttpResponse response) |
| | | 1321 | | { |
| | 31 | 1322 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 1323 | | { |
| | 30 | 1324 | | Log.Debug("Applying KestrunResponse to HttpResponse, StatusCode={StatusCode}, ContentType={ContentType}, Bod |
| | 30 | 1325 | | StatusCode, ContentType, Body?.GetType().Name ?? "null"); |
| | | 1326 | | } |
| | | 1327 | | |
| | 31 | 1328 | | if (response.StatusCode == StatusCodes.Status304NotModified) |
| | | 1329 | | { |
| | 0 | 1330 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 1331 | | { |
| | 0 | 1332 | | Log.Debug("Response already has status code 304 Not Modified, skipping ApplyTo"); |
| | | 1333 | | } |
| | 0 | 1334 | | return; |
| | | 1335 | | } |
| | 31 | 1336 | | if (!string.IsNullOrEmpty(RedirectUrl)) |
| | | 1337 | | { |
| | 2 | 1338 | | response.Redirect(RedirectUrl); |
| | 2 | 1339 | | return; |
| | | 1340 | | } |
| | | 1341 | | |
| | | 1342 | | try |
| | | 1343 | | { |
| | 29 | 1344 | | EnsureStatus(response); |
| | 29 | 1345 | | ApplyHeadersAndCookies(response); |
| | 29 | 1346 | | ApplyCachingHeaders(response); |
| | | 1347 | | |
| | 29 | 1348 | | await TryEnqueueCallbacks(); |
| | | 1349 | | |
| | 29 | 1350 | | if (Body is not null) |
| | | 1351 | | { |
| | 25 | 1352 | | EnsureContentType(response); |
| | 25 | 1353 | | ApplyContentDispositionHeader(response); |
| | 25 | 1354 | | await WriteBodyAsync(response).ConfigureAwait(false); |
| | | 1355 | | } |
| | | 1356 | | else |
| | | 1357 | | { |
| | 4 | 1358 | | response.ContentType = null; |
| | 4 | 1359 | | response.ContentLength = null; |
| | 4 | 1360 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 1361 | | { |
| | 4 | 1362 | | Log.Debug("Status-only: HasStarted={HasStarted} CL={CL} CT='{CT}'", |
| | 4 | 1363 | | response.HasStarted, response.ContentLength, response.ContentType); |
| | | 1364 | | } |
| | | 1365 | | } |
| | 29 | 1366 | | } |
| | 0 | 1367 | | catch (Exception ex) |
| | | 1368 | | { |
| | 0 | 1369 | | Console.WriteLine($"Error applying response: {ex.Message}"); |
| | | 1370 | | // Optionally, you can log the exception or handle it as needed |
| | 0 | 1371 | | throw; |
| | | 1372 | | } |
| | 31 | 1373 | | } |
| | | 1374 | | |
| | | 1375 | | /// <summary> |
| | | 1376 | | /// Attempts to enqueue any registered callback requests using the ICallbackDispatcher service. |
| | | 1377 | | /// </summary> |
| | | 1378 | | private async ValueTask TryEnqueueCallbacks() |
| | | 1379 | | { |
| | 29 | 1380 | | if (CallbackPlan.Count == 0) |
| | | 1381 | | { |
| | 28 | 1382 | | return; |
| | | 1383 | | } |
| | | 1384 | | |
| | | 1385 | | // Prevent multiple enqueues |
| | 1 | 1386 | | if (Interlocked.Exchange(ref CallbacksEnqueuedFlag, 1) == 1) |
| | | 1387 | | { |
| | 0 | 1388 | | return; |
| | | 1389 | | } |
| | | 1390 | | |
| | 1 | 1391 | | var log = KrContext.Host.Logger; |
| | 1 | 1392 | | if (log.IsEnabled(LogEventLevel.Information)) |
| | | 1393 | | { |
| | 1 | 1394 | | log.Information("Enqueuing {Count} callbacks for dispatch.", CallbackPlan.Count); |
| | | 1395 | | } |
| | | 1396 | | |
| | | 1397 | | try |
| | | 1398 | | { |
| | 1 | 1399 | | var httpCtx = KrContext.HttpContext; |
| | | 1400 | | |
| | | 1401 | | // Resolve DI services while request is alive |
| | 1 | 1402 | | var dispatcher = httpCtx.RequestServices.GetService<ICallbackDispatcher>(); |
| | 1 | 1403 | | if (dispatcher is null) |
| | | 1404 | | { |
| | 1 | 1405 | | log.Warning("Callbacks present but no ICallbackDispatcher registered. Count={Count}", CallbackPlan.Count |
| | 1 | 1406 | | return; |
| | | 1407 | | } |
| | | 1408 | | |
| | 0 | 1409 | | var urlResolver = httpCtx.RequestServices.GetRequiredService<ICallbackUrlResolver>(); |
| | 0 | 1410 | | var serializer = httpCtx.RequestServices.GetRequiredService<ICallbackBodySerializer>(); |
| | 0 | 1411 | | var options = httpCtx.RequestServices.GetService<CallbackDispatchOptions>() ?? new CallbackDispatchOptions() |
| | | 1412 | | |
| | 0 | 1413 | | foreach (var plan in CallbackPlan) |
| | | 1414 | | { |
| | | 1415 | | try |
| | | 1416 | | { |
| | 0 | 1417 | | var req = CallbackRequestFactory.FromPlan(plan, KrContext, urlResolver, serializer, options); |
| | | 1418 | | |
| | 0 | 1419 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 1420 | | { |
| | 0 | 1421 | | log.Debug("Enqueue callback. CallbackId={CallbackId} Url={Url}", req.CallbackId, req.TargetUrl); |
| | | 1422 | | } |
| | | 1423 | | |
| | 0 | 1424 | | await dispatcher.EnqueueAsync(req, CancellationToken.None).ConfigureAwait(false); |
| | 0 | 1425 | | } |
| | 0 | 1426 | | catch (Exception ex) |
| | | 1427 | | { |
| | 0 | 1428 | | log.Error(ex, "Failed to enqueue callback. CallbackId={CallbackId}", plan.CallbackId); |
| | 0 | 1429 | | } |
| | 0 | 1430 | | } |
| | 0 | 1431 | | } |
| | 0 | 1432 | | catch (Exception ex) |
| | | 1433 | | { |
| | 0 | 1434 | | log.Error(ex, "Unexpected error while scheduling callbacks."); |
| | 0 | 1435 | | } |
| | 29 | 1436 | | } |
| | | 1437 | | |
| | | 1438 | | /// <summary> |
| | | 1439 | | /// Ensures the HTTP response has the correct status code and content type. |
| | | 1440 | | /// </summary> |
| | | 1441 | | /// <param name="response">The HTTP response to apply the status and content type to.</param> |
| | | 1442 | | private void EnsureContentType(HttpResponse response) |
| | | 1443 | | { |
| | 25 | 1444 | | if (ContentType != response.ContentType) |
| | | 1445 | | { |
| | 25 | 1446 | | if (!string.IsNullOrEmpty(ContentType) && |
| | 25 | 1447 | | IsTextBasedContentType(ContentType) && |
| | 25 | 1448 | | !ContentType.Contains("charset=", StringComparison.OrdinalIgnoreCase)) |
| | | 1449 | | { |
| | 5 | 1450 | | ContentType = ContentType.TrimEnd(';') + $"; charset={AcceptCharset.WebName}"; |
| | | 1451 | | } |
| | 25 | 1452 | | response.ContentType = ContentType; |
| | | 1453 | | } |
| | 25 | 1454 | | } |
| | | 1455 | | |
| | | 1456 | | /// <summary> |
| | | 1457 | | /// Ensures the HTTP response has the correct status code. |
| | | 1458 | | /// </summary> |
| | | 1459 | | /// <param name="response">The HTTP response to apply the status code to.</param> |
| | | 1460 | | private void EnsureStatus(HttpResponse response) |
| | | 1461 | | { |
| | 29 | 1462 | | if (StatusCode != response.StatusCode) |
| | | 1463 | | { |
| | 2 | 1464 | | response.StatusCode = StatusCode; |
| | | 1465 | | } |
| | 29 | 1466 | | } |
| | | 1467 | | |
| | | 1468 | | /// <summary> |
| | | 1469 | | /// Adds caching headers to the response based on the provided CacheControlHeaderValue options. |
| | | 1470 | | /// </summary> |
| | | 1471 | | /// <param name="response">The HTTP response to apply caching headers to.</param> |
| | | 1472 | | /// <exception cref="ArgumentNullException">Thrown when options is null.</exception> |
| | | 1473 | | public void ApplyCachingHeaders(HttpResponse response) |
| | | 1474 | | { |
| | 29 | 1475 | | if (CacheControl is not null) |
| | | 1476 | | { |
| | 1 | 1477 | | response.Headers.CacheControl = CacheControl.ToString(); |
| | | 1478 | | } |
| | 29 | 1479 | | } |
| | | 1480 | | |
| | | 1481 | | /// <summary> |
| | | 1482 | | /// Applies the Content-Disposition header to the HTTP response. |
| | | 1483 | | /// </summary> |
| | | 1484 | | /// <param name="response">The HTTP response to apply the header to.</param> |
| | | 1485 | | private void ApplyContentDispositionHeader(HttpResponse response) |
| | | 1486 | | { |
| | 25 | 1487 | | if (ContentDisposition.Type == ContentDispositionType.NoContentDisposition) |
| | | 1488 | | { |
| | 23 | 1489 | | return; |
| | | 1490 | | } |
| | | 1491 | | |
| | 2 | 1492 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | | 1493 | | { |
| | 2 | 1494 | | Log.Debug("Setting Content-Disposition header, Type={Type}, FileName={FileName}", |
| | 2 | 1495 | | ContentDisposition.Type, ContentDisposition.FileName); |
| | | 1496 | | } |
| | | 1497 | | |
| | 2 | 1498 | | var dispositionValue = ContentDisposition.Type switch |
| | 2 | 1499 | | { |
| | 2 | 1500 | | ContentDispositionType.Attachment => "attachment", |
| | 0 | 1501 | | ContentDispositionType.Inline => "inline", |
| | 0 | 1502 | | _ => throw new InvalidOperationException("Invalid Content-Disposition type") |
| | 2 | 1503 | | }; |
| | | 1504 | | |
| | 2 | 1505 | | if (string.IsNullOrEmpty(ContentDisposition.FileName) && Body is IFileInfo fi) |
| | | 1506 | | { |
| | | 1507 | | // default filename: use the file's name |
| | 1 | 1508 | | ContentDisposition.FileName = fi.Name; |
| | | 1509 | | } |
| | | 1510 | | |
| | 2 | 1511 | | if (!string.IsNullOrEmpty(ContentDisposition.FileName)) |
| | | 1512 | | { |
| | 2 | 1513 | | var escapedFileName = WebUtility.UrlEncode(ContentDisposition.FileName); |
| | 2 | 1514 | | dispositionValue += $"; filename=\"{escapedFileName}\""; |
| | | 1515 | | } |
| | | 1516 | | |
| | 2 | 1517 | | response.Headers.Append("Content-Disposition", dispositionValue); |
| | 2 | 1518 | | } |
| | | 1519 | | |
| | | 1520 | | /// <summary> |
| | | 1521 | | /// Applies headers and cookies to the HTTP response. |
| | | 1522 | | /// </summary> |
| | | 1523 | | /// <param name="response">The HTTP response to apply the headers and cookies to.</param> |
| | | 1524 | | private void ApplyHeadersAndCookies(HttpResponse response) |
| | | 1525 | | { |
| | 29 | 1526 | | if (Headers is not null) |
| | | 1527 | | { |
| | 58 | 1528 | | foreach (var kv in Headers) |
| | | 1529 | | { |
| | 0 | 1530 | | response.Headers[kv.Key] = kv.Value; |
| | | 1531 | | } |
| | | 1532 | | } |
| | 29 | 1533 | | if (Cookies is not null) |
| | | 1534 | | { |
| | 6 | 1535 | | foreach (var cookie in Cookies) |
| | | 1536 | | { |
| | 2 | 1537 | | response.Headers.Append("Set-Cookie", cookie); |
| | | 1538 | | } |
| | | 1539 | | } |
| | 29 | 1540 | | } |
| | | 1541 | | |
| | | 1542 | | /// <summary> |
| | | 1543 | | /// Writes the response body to the HTTP response. |
| | | 1544 | | /// </summary> |
| | | 1545 | | /// <param name="response">The HTTP response to write to.</param> |
| | | 1546 | | /// <returns>A task representing the asynchronous operation.</returns> |
| | | 1547 | | private async Task WriteBodyAsync(HttpResponse response) |
| | | 1548 | | { |
| | 25 | 1549 | | var bodyValue = Body; // capture to avoid nullability warnings when mutated in default |
| | | 1550 | | switch (bodyValue) |
| | | 1551 | | { |
| | | 1552 | | case IFileInfo fileInfo: |
| | 1 | 1553 | | Log.Debug("Sending file {FileName} (Length={Length})", fileInfo.Name, fileInfo.Length); |
| | 1 | 1554 | | response.ContentLength = fileInfo.Length; |
| | 1 | 1555 | | response.Headers.LastModified = fileInfo.LastModified.ToString("R"); |
| | 1 | 1556 | | await response.SendFileAsync( |
| | 1 | 1557 | | file: fileInfo, |
| | 1 | 1558 | | offset: 0, |
| | 1 | 1559 | | count: fileInfo.Length, |
| | 1 | 1560 | | cancellationToken: response.HttpContext.RequestAborted |
| | 1 | 1561 | | ); |
| | 1 | 1562 | | break; |
| | | 1563 | | |
| | | 1564 | | case byte[] bytes: |
| | 1 | 1565 | | response.ContentLength = bytes.LongLength; |
| | 1 | 1566 | | await response.Body.WriteAsync(bytes, response.HttpContext.RequestAborted); |
| | 1 | 1567 | | await response.Body.FlushAsync(response.HttpContext.RequestAborted); |
| | 1 | 1568 | | break; |
| | | 1569 | | |
| | | 1570 | | case Stream stream: |
| | 2 | 1571 | | var seekable = stream.CanSeek; |
| | 2 | 1572 | | Log.Debug("Sending stream (seekable={Seekable}, len={Len})", |
| | 2 | 1573 | | seekable, seekable ? stream.Length : -1); |
| | | 1574 | | |
| | 2 | 1575 | | if (seekable) |
| | | 1576 | | { |
| | 1 | 1577 | | response.ContentLength = stream.Length; |
| | 1 | 1578 | | stream.Position = 0; |
| | | 1579 | | } |
| | | 1580 | | else |
| | | 1581 | | { |
| | 1 | 1582 | | response.ContentLength = null; |
| | | 1583 | | } |
| | | 1584 | | |
| | | 1585 | | const int BufferSize = 64 * 1024; // 64 KB |
| | 2 | 1586 | | var buffer = ArrayPool<byte>.Shared.Rent(BufferSize); |
| | | 1587 | | try |
| | | 1588 | | { |
| | | 1589 | | int bytesRead; |
| | 4 | 1590 | | while ((bytesRead = await stream.ReadAsync(buffer.AsMemory(0, BufferSize), response.HttpContext.Requ |
| | | 1591 | | { |
| | 2 | 1592 | | await response.Body.WriteAsync(buffer.AsMemory(0, bytesRead), response.HttpContext.RequestAborte |
| | | 1593 | | } |
| | 2 | 1594 | | } |
| | | 1595 | | finally |
| | | 1596 | | { |
| | 2 | 1597 | | ArrayPool<byte>.Shared.Return(buffer); |
| | | 1598 | | } |
| | 2 | 1599 | | await response.Body.FlushAsync(response.HttpContext.RequestAborted); |
| | 2 | 1600 | | break; |
| | | 1601 | | |
| | | 1602 | | case string str: |
| | 21 | 1603 | | var data = AcceptCharset.GetBytes(str); |
| | 21 | 1604 | | response.ContentLength = data.Length; |
| | 21 | 1605 | | await response.Body.WriteAsync(data, response.HttpContext.RequestAborted); |
| | 21 | 1606 | | await response.Body.FlushAsync(response.HttpContext.RequestAborted); |
| | 21 | 1607 | | break; |
| | | 1608 | | |
| | | 1609 | | default: |
| | 0 | 1610 | | var bodyType = bodyValue?.GetType().Name ?? "null"; |
| | 0 | 1611 | | Body = "Unsupported body type: " + bodyType; |
| | 0 | 1612 | | Log.Warning("Unsupported body type: {BodyType}", bodyType); |
| | 0 | 1613 | | response.StatusCode = StatusCodes.Status500InternalServerError; |
| | 0 | 1614 | | response.ContentType = "text/plain; charset=utf-8"; |
| | 0 | 1615 | | response.ContentLength = Body.ToString()?.Length ?? null; |
| | | 1616 | | break; |
| | | 1617 | | } |
| | 25 | 1618 | | } |
| | | 1619 | | #endregion |
| | | 1620 | | } |