Skip to content

Commit 238f78e

Browse files
committed
fallback to utf-8 when provided an invalid charset
1 parent 91ce984 commit 238f78e

1 file changed

Lines changed: 37 additions & 3 deletions

File tree

src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1609,9 +1609,43 @@ private void WriteWebResponseDebugInfo(HttpResponseMessage response)
16091609

16101610
if (ContentHelper.IsTextBasedContentType(ContentHelper.GetContentType(response)))
16111611
{
1612-
debugBuilder.AppendLine(
1613-
response.Content.ReadAsStringAsync(_cancelToken.Token)
1614-
.GetAwaiter().GetResult());
1612+
string body;
1613+
1614+
try
1615+
{
1616+
// Normal path
1617+
body = response.Content
1618+
.ReadAsStringAsync(_cancelToken.Token)
1619+
.GetAwaiter().GetResult();
1620+
}
1621+
catch (InvalidOperationException)
1622+
{
1623+
// Fallback for invalid charset (e.g., "utf8")
1624+
var headers = response.Content.Headers;
1625+
string charset = headers?.ContentType?.CharSet;
1626+
1627+
Encoding encoding;
1628+
1629+
try
1630+
{
1631+
encoding = !string.IsNullOrEmpty(charset)
1632+
? Encoding.GetEncoding(charset)
1633+
: Encoding.UTF8;
1634+
}
1635+
catch (ArgumentException)
1636+
{
1637+
// Final fallback
1638+
encoding = Encoding.UTF8;
1639+
}
1640+
1641+
var bytes = response.Content
1642+
.ReadAsByteArrayAsync(_cancelToken.Token)
1643+
.GetAwaiter().GetResult();
1644+
1645+
body = encoding.GetString(bytes);
1646+
}
1647+
1648+
debugBuilder.AppendLine(body);
16151649
}
16161650
else
16171651
{

0 commit comments

Comments
 (0)