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