From b4f330ae430bbd1d86904e2c4ac4a498cda71161 Mon Sep 17 00:00:00 2001 From: wuyangfan Date: Mon, 25 May 2026 10:57:35 +0800 Subject: [PATCH] fix: honor htmlEscape in System.Text.Json ToJson implementation Use JavaScriptEncoder.Default when htmlEscape is true so STJSON builds match the Newtonsoft behavior for HTML-safe profiler JSON output. Fixes #680 Co-authored-by: Cursor --- src/MiniProfiler.Shared/Internal/ExtensionMethods.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/MiniProfiler.Shared/Internal/ExtensionMethods.cs b/src/MiniProfiler.Shared/Internal/ExtensionMethods.cs index 2b5a6b0d..7c86eb54 100644 --- a/src/MiniProfiler.Shared/Internal/ExtensionMethods.cs +++ b/src/MiniProfiler.Shared/Internal/ExtensionMethods.cs @@ -7,6 +7,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Serialization; #elif STJSON +using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; #endif @@ -134,6 +135,13 @@ public static string ToJson(this List? guids) private static readonly JsonSerializerOptions defaultSettings = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + private static readonly JsonSerializerOptions htmlEscapeSettings = new() + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Encoder = JavaScriptEncoder.Default, }; /// @@ -142,10 +150,9 @@ public static string ToJson(this List? guids) /// The to serialize. /// Whether to HTML escape the output. [return: NotNullIfNotNull(nameof(profiler))] - [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Compatibility across versions")] public static string? ToJson(this MiniProfiler? profiler, bool htmlEscape = false) => profiler != default - ? JsonSerializer.Serialize(profiler, defaultSettings) + ? JsonSerializer.Serialize(profiler, htmlEscape ? htmlEscapeSettings : defaultSettings) : null; ///