From 24c6416940dec92ab147002c8b77e3786906ac13 Mon Sep 17 00:00:00 2001 From: Ryan Yates Date: Sun, 9 Aug 2026 18:13:03 +0100 Subject: [PATCH] fallback to utf-8 when provided an invalid charset --- .../Common/WebRequestPSCmdlet.Common.cs | 40 +++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index f1a455974b9..b74703d7459 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1609,9 +1609,43 @@ private void WriteWebResponseDebugInfo(HttpResponseMessage response) if (ContentHelper.IsTextBasedContentType(ContentHelper.GetContentType(response))) { - debugBuilder.AppendLine( - response.Content.ReadAsStringAsync(_cancelToken.Token) - .GetAwaiter().GetResult()); + string body; + + try + { + // Normal path + body = response.Content + .ReadAsStringAsync(_cancelToken.Token) + .GetAwaiter().GetResult(); + } + catch (InvalidOperationException) + { + // Fallback for invalid charset (e.g., "utf8") + var headers = response.Content.Headers; + string charset = headers?.ContentType?.CharSet; + + Encoding encoding; + + try + { + encoding = !string.IsNullOrEmpty(charset) + ? Encoding.GetEncoding(charset) + : Encoding.UTF8; + } + catch (ArgumentException) + { + // Final fallback + encoding = Encoding.UTF8; + } + + var bytes = response.Content + .ReadAsByteArrayAsync(_cancelToken.Token) + .GetAwaiter().GetResult(); + + body = encoding.GetString(bytes); + } + + debugBuilder.AppendLine(body); } else {