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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// The valid values for the -Authentication parameter for Invoke-RestMethod and Invoke-WebRequest.
    /// </summary>
    public enum WebAuthenticationType
    {
        /// <summary>
        /// No authentication. Default.
        /// </summary>
        None,

        /// <summary>
        /// RFC-7617 Basic Authentication. Requires -Credential.
        /// </summary>
        Basic,

        /// <summary>
        /// RFC-6750 OAuth 2.0 Bearer Authentication. Requires -Token.
        /// </summary>
        Bearer,

        /// <summary>
        /// RFC-6750 OAuth 2.0 Bearer Authentication. Requires -Token.
        /// </summary>
        OAuth,
    }

    // WebSslProtocol is used because not all SslProtocols are supported by HttpClientHandler.
    // Also SslProtocols.Default is not the "default" for HttpClientHandler as SslProtocols.Ssl3 is not supported.
    /// <summary>
    /// The valid values for the -SslProtocol parameter for Invoke-RestMethod and Invoke-WebRequest.
    /// </summary>
    [Flags]
    public enum WebSslProtocol
    {
        /// <summary>
        /// No SSL protocol will be set and the system defaults will be used.
        /// </summary>
        Default = SslProtocols.None,

        /// <summary>
        /// Specifies the TLS 1.0 is obsolete. Using this value now defaults to TLS 1.2.
        /// </summary>
        Tls = SslProtocols.Tls12,

        /// <summary>
        /// Specifies the TLS 1.1 is obsolete. Using this value now defaults to TLS 1.2.
        /// </summary>
        Tls11 = SslProtocols.Tls12,

        /// <summary>
        /// Specifies the TLS 1.2 security protocol. The TLS protocol is defined in IETF RFC 5246.
        /// </summary>
        Tls12 = SslProtocols.Tls12,

        /// <summary>
        /// Specifies the TLS 1.3 security protocol. The TLS protocol is defined in IETF RFC 8446.
        /// </summary>
        Tls13 = SslProtocols.Tls13
    }

    /// <summary>
    /// Base class for Invoke-RestMethod and Invoke-WebRequest commands.
    /// </summary>
    public abstract class WebRequestPSCmdlet : PSCmdlet, IDisposable
    {
        #region Fields

        /// <summary>
        /// Used to prefix the headers in debug and verbose messaging.
        /// </summary>
        internal const string DebugHeaderPrefix = "--- ";

        /// <summary>
        /// Cancellation token source.
        /// </summary>
        internal CancellationTokenSource _cancelToken = null;

        /// <summary>
        /// Automatically follow Rel Links.
        /// </summary>
        internal bool _followRelLink = false;

        /// <summary>
        /// Maximum number of Rel Links to follow.
        /// </summary>
        internal int _maximumFollowRelLink = int.MaxValue;

        /// <summary>
        /// Maximum number of Redirects to follow.
        /// </summary>
        internal int _maximumRedirection;

        /// <summary>
        /// Parse Rel Links.
        /// </summary>
        internal bool _parseRelLink = false;

        /// <summary>
        /// Automatically follow Rel Links.
        /// </summary>
        internal Dictionary<string, string> _relationLink = null;

        /// <summary>
        /// The current size of the local file being resumed.
        /// </summary>
        private long _resumeFileSize = 0;

        /// <summary>
        /// The remote endpoint returned a 206 status code indicating successful resume.
        /// </summary>
        private bool _resumeSuccess = false;

        /// <summary>
        /// True if the Dispose() method has already been called to cleanup Disposable fields.
        /// </summary>
        private bool _disposed = false;

        #endregion Fields

        #region Virtual Properties

        #region URI

        /// <summary>
        /// Deprecated. Gets or sets UseBasicParsing. This has no affect on the operation of the Cmdlet.
        /// </summary>
        [Parameter(DontShow = true)]
        public virtual SwitchParameter UseBasicParsing { get; set; } = true;

        /// <summary>
        /// Gets or sets the Uri property.
        /// </summary>
        [Parameter(Position = 0, Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public virtual Uri Uri { get; set; }

        #endregion URI

        #region HTTP Version

        /// <summary>
        /// Gets or sets the HTTP Version property.
        /// </summary>
        [Parameter]
        [ArgumentToVersionTransformation]
        [HttpVersionCompletions]
        public virtual Version HttpVersion { get; set; }

        #endregion HTTP Version

        #region Session
        /// <summary>
        /// Gets or sets the Session property.
        /// </summary>
        [Parameter]
        public virtual WebRequestSession WebSession { get; set; }

        /// <summary>
        /// Gets or sets the SessionVariable property.
        /// </summary>
        [Parameter]
        [Alias("SV")]
        public virtual string SessionVariable { get; set; }

        #endregion Session

        #region Authorization and Credentials

        /// <summary>
        /// Gets or sets the AllowUnencryptedAuthentication property.
        /// </summary>
        [Parameter]
        public virtual SwitchParameter AllowUnencryptedAuthentication { get; set; }

        /// <summary>
        /// Gets or sets the Authentication property used to determine the Authentication method for the web session.
        /// Authentication does not work with UseDefaultCredentials.
        /// Authentication over unencrypted sessions requires AllowUnencryptedAuthentication.
        /// Basic: Requires Credential.
        /// OAuth/Bearer: Requires Token.
        /// </summary>
        [Parameter]
        public virtual WebAuthenticationType Authentication { get; set; } = WebAuthenticationType.None;

        /// <summary>
        /// Gets or sets the Credential property.
        /// </summary>
        [Parameter]
        [Credential]
        public virtual PSCredential Credential { get; set; }

        /// <summary>
        /// Gets or sets the UseDefaultCredentials property.
        /// </summary>
        [Parameter]
        public virtual SwitchParameter UseDefaultCredentials { get; set; }

        /// <summary>
        /// Gets or sets the CertificateThumbprint property.
        /// </summary>
        [Parameter]
        [ValidateNotNullOrEmpty]
        public virtual string CertificateThumbprint { get; set; }

        /// <summary>
        /// Gets or sets the Certificate property.
        /// </summary>
        [Parameter]
        [ValidateNotNull]
        public virtual X509Certificate Certificate { get; set; }

        /// <summary>
        /// Gets or sets the SkipCertificateCheck property.
        /// </summary>
        [Parameter]
        public virtual SwitchParameter SkipCertificateCheck { get; set; }

        /// <summary>
        /// Gets or sets the TLS/SSL protocol used by the Web Cmdlet.
        /// </summary>
        [Parameter]
        public virtual WebSslProtocol SslProtocol { get; set; } = WebSslProtocol.Default;

        /// <summary>
        /// Gets or sets the Token property. Token is required by Authentication OAuth and Bearer.
        /// </summary>
        [Parameter]
        public virtual SecureString Token { get; set; }

        #endregion Authorization and Credentials

        #region Headers

        /// <summary>
        /// Gets or sets the UserAgent property.
        /// </summary>
        [Parameter]
        public virtual string UserAgent { get; set; }

        /// <summary>
        /// Gets or sets the DisableKeepAlive property.
        /// </summary>
        [Parameter]
        public virtual SwitchParameter DisableKeepAlive { get; set; }

        /// <summary>
        /// Gets or sets the ConnectionTimeoutSeconds property.
        /// </summary>
        /// <remarks>
        /// This property applies to sending the request and receiving the response headers only.
        /// </remarks>
        [Alias("TimeoutSec")]
        [Parameter]
        [ValidateRange(0, int.MaxValue)]
        public virtual int ConnectionTimeoutSeconds { get; set; }

        /// <summary>
        /// Gets or sets the OperationTimeoutSeconds property.
        /// </summary>
        /// <remarks>
        /// This property applies to each read operation when receiving the response body.
        /// </remarks>
        [Parameter]
        [ValidateRange(0, int.MaxValue)]
        public virtual int OperationTimeoutSeconds { get; set; }

        /// <summary>
        /// Gets or sets the Headers property.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        [Parameter]
        public virtual IDictionary Headers { get; set; }

        /// <summary>
        /// Gets or sets the SkipHeaderValidation property.
        /// </summary>
        /// <remarks>
        /// This property adds headers to the request's header collection without validation.
        /// </remarks>
        [Parameter]
        public virtual SwitchParameter SkipHeaderValidation { get; set; }

        #endregion Headers

        #region Redirect

        /// <summary>
        /// Gets or sets the AllowInsecureRedirect property used to follow HTTP redirects from HTTPS.
        /// </summary>
        [Parameter]
        public virtual SwitchParameter AllowInsecureRedirect { get; set; }

        /// <summary>
        /// Gets or sets the RedirectMax property.
        /// </summary>
        [Parameter]
        [ValidateRange(0, int.MaxValue)]
        public virtual int MaximumRedirection { get; set; } = -1;

        /// <summary>
        /// Gets or sets the MaximumRetryCount property, which determines the number of retries of a failed web request.
        /// </summary>
        [Parameter]
        [ValidateRange(0, int.MaxValue)]
        public virtual int MaximumRetryCount { get; set; }

        /// <summary>
        /// Gets or sets the PreserveAuthorizationOnRedirect property.
        /// </summary>
        /// <remarks>
        /// This property overrides compatibility with web requests on Windows.
        /// On FullCLR (WebRequest), authorization headers are stripped during redirect.
        /// CoreCLR (HTTPClient) does not have this behavior so web requests that work on
        /// PowerShell/FullCLR can fail with PowerShell/CoreCLR. To provide compatibility,
        /// we'll detect requests with an Authorization header and automatically strip
        /// the header when the first redirect occurs. This switch turns off this logic for
        /// edge cases where the authorization header needs to be preserved across redirects.
        /// </remarks>
        [Parameter]
        public virtual SwitchParameter PreserveAuthorizationOnRedirect { get; set; }

        /// <summary>
        /// Gets or sets the RetryIntervalSec property, which determines the number seconds between retries.
        /// </summary>
        [Parameter]
        [ValidateRange(1, int.MaxValue)]
        public virtual int RetryIntervalSec { get; set; } = 5;

        #endregion Redirect

        #region Method

        /// <summary>
        /// Gets or sets the Method property.
        /// </summary>
        [Parameter(ParameterSetName = "StandardMethod")]
        [Parameter(ParameterSetName = "StandardMethodNoProxy")]
        public virtual WebRequestMethod Method { get; set; } = WebRequestMethod.Default;

        /// <summary>
        /// Gets or sets the CustomMethod property.
        /// </summary>
        [Parameter(Mandatory = true, ParameterSetName = "CustomMethod")]
        [Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")]
        [Alias("CM")]
        [ValidateNotNullOrEmpty]
        public virtual string CustomMethod { get => _customMethod; set => _customMethod = value.ToUpperInvariant(); }

        private string _customMethod;

        /// <summary>
        /// Gets or sets the PreserveHttpMethodOnRedirect property.
        /// </summary>
        [Parameter]
        public virtual SwitchParameter PreserveHttpMethodOnRedirect { get; set; }

        /// <summary>
        /// Gets or sets the UnixSocket property.
        /// </summary>
        [Parameter]
        [ValidateNotNullOrEmpty]
        public virtual UnixDomainSocketEndPoint UnixSocket { get; set; }

        #endregion Method

        #region NoProxy

        /// <summary>
        /// Gets or sets the NoProxy property.
        /// </summary>
        [Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")]
        [Parameter(Mandatory = true, ParameterSetName = "StandardMethodNoProxy")]
        public virtual SwitchParameter NoProxy { get; set; }

        #endregion NoProxy

        #region Proxy

        /// <summary>
        /// Gets or sets the Proxy property.
        /// </summary>
        [Parameter(ParameterSetName = "StandardMethod")]
        [Parameter(ParameterSetName = "CustomMethod")]
        public virtual Uri Proxy { get; set; }

        /// <summary>
        /// Gets or sets the ProxyCredential property.
        /// </summary>
        [Parameter(ParameterSetName = "StandardMethod")]
        [Parameter(ParameterSetName = "CustomMethod")]
        [Credential]
        public virtual PSCredential ProxyCredential { get; set; }

        /// <summary>
        /// Gets or sets the ProxyUseDefaultCredentials property.
        /// </summary>
        [Parameter(ParameterSetName = "StandardMethod")]
        [Parameter(ParameterSetName = "CustomMethod")]
        public virtual SwitchParameter ProxyUseDefaultCredentials { get; set; }

        #endregion Proxy

        #region Input

        /// <summary>
        /// Gets or sets the Body property.
        /// </summary>
        [Parameter(ValueFromPipeline = true)]
        public virtual object Body { get; set; }

        /// <summary>
        /// Dictionary for use with RFC-7578 multipart/form-data submissions.
        /// Keys are form fields and their respective values are form values.
        /// A value may be a collection of form values or single form value.
        /// </summary>
        [Parameter]
        public virtual IDictionary Form { get; set; }

        /// <summary>
        /// Gets or sets the ContentType property.
        /// </summary>
        [Parameter]
        public virtual string ContentType { get; set; }

        /// <summary>
        /// Gets or sets the TransferEncoding property.
        /// </summary>
        [Parameter]
        [ValidateSet("chunked", "compress", "deflate", "gzip", "identity", IgnoreCase = true)]
        public virtual string TransferEncoding { get; set; }

        /// <summary>
        /// Gets or sets the InFile property.
        /// </summary>
        [Parameter]
        [ValidateNotNullOrEmpty]
        public virtual string InFile { get; set; }

        /// <summary>
        /// Keep the original file path after the resolved provider path is assigned to InFile.
        /// </summary>
        private string _originalFilePath;

        #endregion Input

        #region Output

        /// <summary>
        /// Gets or sets the OutFile property.
        /// </summary>
        [Parameter]
        [ValidateNotNullOrEmpty]
        public virtual string OutFile { get; set; }

        /// <summary>
        /// Gets or sets the PassThrough property.
        /// </summary>
        [Parameter]
        public virtual SwitchParameter PassThru { get; set; }

        /// <summary>
        /// Resumes downloading a partial or incomplete file. OutFile is required.
        /// </summary>
        [Parameter]
        public virtual SwitchParameter Resume { get; set; }

        /// <summary>
        /// Gets or sets whether to skip checking HTTP status for error codes.
        /// </summary>
        [Parameter]
        public virtual SwitchParameter SkipHttpErrorCheck { get; set; }

        #endregion Output

        #endregion Virtual Properties

        #region Helper Properties

        internal string QualifiedOutFile => QualifyFilePath(OutFile);

        internal string _qualifiedOutFile;

        internal bool ShouldCheckHttpStatus => !SkipHttpErrorCheck;

        /// <summary>
        /// Determines whether writing to a file should Resume and append rather than overwrite.
        /// </summary>
        internal bool ShouldResume => Resume.IsPresent && _resumeSuccess;

        internal bool ShouldSaveToOutFile => !string.IsNullOrEmpty(OutFile);

        internal bool ShouldWriteToPipeline => !ShouldSaveToOutFile || PassThru;

        #endregion Helper Properties

        #region Abstract Methods

        /// <summary>
        /// Read the supplied WebResponse object and push the resulting output into the pipeline.
        /// </summary>
        /// <param name="response">Instance of a WebResponse object to be processed.</param>
        internal abstract void ProcessResponse(HttpResponseMessage response);

        #endregion Abstract Methods

        #region Overrides

        /// <summary>
        /// The main execution method for cmdlets derived from WebRequestPSCmdlet.
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                // Set cmdlet context for write progress
                ValidateParameters();
                PrepareSession();

                // If the request contains an authorization header and PreserveAuthorizationOnRedirect is not set,
                // it needs to be stripped on the first redirect.
                bool keepAuthorizationOnRedirect = PreserveAuthorizationOnRedirect.IsPresent
                                                   && WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization);

                bool handleRedirect = keepAuthorizationOnRedirect || AllowInsecureRedirect || PreserveHttpMethodOnRedirect;

                HttpClient client = GetHttpClient(handleRedirect);

                int followedRelLink = 0;
                Uri uri = Uri;
                do
                {
                    if (followedRelLink > 0)
                    {
                        string linkVerboseMsg = string.Format(
                            CultureInfo.CurrentCulture,
                            WebCmdletStrings.FollowingRelLinkVerboseMsg,
                            uri.AbsoluteUri);

                        WriteVerbose(linkVerboseMsg);
                    }

                    using (HttpRequestMessage request = GetRequest(uri))
                    {
                        FillRequestStream(request);
                        try
                        {
                            _maximumRedirection = WebSession.MaximumRedirection;

                            using HttpResponseMessage response = GetResponse(client, request, handleRedirect);

                            bool _isSuccess = response.IsSuccessStatusCode;

                            // Check if the Resume range was not satisfiable because the file already completed downloading.
                            // This happens when the local file is the same size as the remote file.
                            if (Resume.IsPresent
                                && response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable
                                && response.Content.Headers.ContentRange.HasLength
                                && response.Content.Headers.ContentRange.Length == _resumeFileSize)
                            {
                                _isSuccess = true;
                                WriteVerbose(string.Format(
                                    CultureInfo.CurrentCulture,
                                    WebCmdletStrings.OutFileWritingSkipped,
                                    OutFile));

                                // Disable writing to the OutFile.
                                OutFile = null;
                            }

                            // Detect insecure redirection.
                            if (!AllowInsecureRedirect)
                            {
                                // We will skip detection if either of the URIs is relative, because the 'Scheme' property is not supported on a relative URI.
                                // If we have to skip the check, an error may be thrown later if it's actually an insecure https-to-http redirect.
                                bool originIsHttps = response.RequestMessage.RequestUri.IsAbsoluteUri && response.RequestMessage.RequestUri.Scheme == "https";
                                bool destinationIsHttp = response.Headers.Location is not null && response.Headers.Location.IsAbsoluteUri && response.Headers.Location.Scheme == "http";

                                if (originIsHttps && destinationIsHttp)
                                {
                                    ErrorRecord er = new(new InvalidOperationException(), "InsecureRedirection", ErrorCategory.InvalidOperation, request);
                                    er.ErrorDetails = new ErrorDetails(WebCmdletStrings.InsecureRedirection);
                                    ThrowTerminatingError(er);
                                }
                            }

                            if (ShouldCheckHttpStatus && !_isSuccess)
                            {
                                string message = string.Format(
                                    CultureInfo.CurrentCulture,
                                    WebCmdletStrings.ResponseStatusCodeFailure,
                                    (int)response.StatusCode,
                                    response.ReasonPhrase);

                                HttpResponseException httpEx = new(message, response);
                                ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request);
                                string detailMsg = string.Empty;
                                try
                                {
                                    string contentType = ContentHelper.GetContentType(response);
                                    long? contentLength = response.Content.Headers.ContentLength;

                                    // We can't use ReadAsStringAsync because it doesn't have per read timeouts
                                    TimeSpan perReadTimeout = ConvertTimeoutSecondsToTimeSpan(OperationTimeoutSeconds);
                                    string characterSet = WebResponseHelper.GetCharacterSet(response);
                                    var responseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token);
                                    int initialCapacity = (int)Math.Min(contentLength ?? StreamHelper.DefaultReadBuffer, StreamHelper.DefaultReadBuffer);
                                    var bufferedStream = new WebResponseContentMemoryStream(responseStream, initialCapacity, this, contentLength, perReadTimeout, _cancelToken.Token);
                                    string error = StreamHelper.DecodeStream(bufferedStream, characterSet, out Encoding encoding, perReadTimeout, _cancelToken.Token);
                                    detailMsg = FormatErrorMessage(error, contentType);
                                }
                                catch (Exception ex)
                                {
                                    // Catch all
                                    er.ErrorDetails = new ErrorDetails(ex.ToString());
                                }

                                if (!string.IsNullOrEmpty(detailMsg))
                                {
                                    er.ErrorDetails = new ErrorDetails(detailMsg);
                                }

                                ThrowTerminatingError(er);
                            }

                            if (_parseRelLink || _followRelLink)
                            {
                                ParseLinkHeader(response);
                            }

                            ProcessResponse(response);
                            UpdateSession(response);

                            // If we hit our maximum redirection count, generate an error.
                            // Errors with redirection counts of greater than 0 are handled automatically by .NET, but are
                            // impossible to detect programmatically when we hit this limit. By handling this ourselves
                            // (and still writing out the result), users can debug actual HTTP redirect problems.
                            if (_maximumRedirection == 0 && IsRedirectCode(response.StatusCode))
                            {
                                ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request);
                                er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded);
                                WriteError(er);
                            }
                        }
                        catch (TimeoutException ex)
                        {
                            ErrorRecord er = new(ex, "OperationTimeoutReached", ErrorCategory.OperationTimeout, null);
                            ThrowTerminatingError(er);
                        }
                        catch (HttpRequestException ex)
                        {
                            ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request);
                            if (ex.InnerException is not null)
                            {
                                er.ErrorDetails = new ErrorDetails(ex.InnerException.Message);
                            }

                            ThrowTerminatingError(er);
                        }
                        finally
                        {
                            _cancelToken?.Dispose();
                            _cancelToken = null;
                        }

                        if (_followRelLink)
                        {
                            if (!_relationLink.ContainsKey("next"))
                            {
                                return;
                            }

                            uri = new Uri(_relationLink["next"]);
                            followedRelLink++;
                        }
                    }
                }
                while (_followRelLink && (followedRelLink < _maximumFollowRelLink));
            }
            catch (CryptographicException ex)
            {
                ErrorRecord er = new(ex, "WebCmdletCertificateException", ErrorCategory.SecurityError, null);
                ThrowTerminatingError(er);
            }
            catch (NotSupportedException ex)
            {
                ErrorRecord er = new(ex, "WebCmdletIEDomNotSupportedException", ErrorCategory.NotImplemented, null);
                ThrowTerminatingError(er);
            }
        }

        /// <summary>
        /// To implement ^C.
        /// </summary>
        protected override void StopProcessing() => _cancelToken?.Cancel();

        /// <summary>
        /// Disposes the associated WebSession if it is not being used as part of a persistent session.
        /// </summary>
        /// <param name="disposing">True when called from Dispose() and false when called from finalizer.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing && !IsPersistentSession())
                {
                    WebSession?.Dispose();
                    WebSession = null;
                }

                _disposed = true;
            }
        }

        /// <summary>
        /// Disposes the associated WebSession if it is not being used as part of a persistent session.
        /// </summary>
        public void Dispose()
        {
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }

        #endregion Overrides

        #region Virtual Methods

        internal virtual void ValidateParameters()
        {
            // Sessions
            if (WebSession is not null && SessionVariable is not null)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, "WebCmdletSessionConflictException");
                ThrowTerminatingError(error);
            }

            // Authentication
            if (UseDefaultCredentials && Authentication != WebAuthenticationType.None)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict, "WebCmdletAuthenticationConflictException");
                ThrowTerminatingError(error);
            }

            if (Authentication != WebAuthenticationType.None && Token is not null && Credential is not null)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, "WebCmdletAuthenticationTokenConflictException");
                ThrowTerminatingError(error);
            }

            if (Authentication == WebAuthenticationType.Basic && Credential is null)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, "WebCmdletAuthenticationCredentialNotSuppliedException");
                ThrowTerminatingError(error);
            }

            if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && Token is null)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, "WebCmdletAuthenticationTokenNotSuppliedException");
                ThrowTerminatingError(error);
            }

            if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None || Credential is not null || UseDefaultCredentials) && Uri.Scheme != "https")
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException");
                ThrowTerminatingError(error);
            }

            // Credentials
            if (UseDefaultCredentials && Credential is not null)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, "WebCmdletCredentialConflictException");
                ThrowTerminatingError(error);
            }

            // Proxy server
            if (ProxyUseDefaultCredentials && ProxyCredential is not null)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, "WebCmdletProxyCredentialConflictException");
                ThrowTerminatingError(error);
            }
            else if (Proxy is null && (ProxyCredential is not null || ProxyUseDefaultCredentials))
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, "WebCmdletProxyUriNotSuppliedException");
                ThrowTerminatingError(error);
            }

            // Request body content
            if (Body is not null && InFile is not null)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, "WebCmdletBodyConflictException");
                ThrowTerminatingError(error);
            }

            if (Body is not null && Form is not null)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, "WebCmdletBodyFormConflictException");
                ThrowTerminatingError(error);
            }

            if (InFile is not null && Form is not null)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, "WebCmdletFormInFileConflictException");
                ThrowTerminatingError(error);
            }

            // Validate InFile path
            if (InFile is not null)
            {
                ErrorRecord errorRecord = null;

                try
                {
                    Collection<string> providerPaths = GetResolvedProviderPathFromPSPath(InFile, out ProviderInfo provider);

                    if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                    {
                        errorRecord = GetValidationError(WebCmdletStrings.NotFilesystemPath, "WebCmdletInFileNotFilesystemPathException", InFile);
                    }
                    else
                    {
                        if (providerPaths.Count > 1)
                        {
                            errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, "WebCmdletInFileMultiplePathsResolvedException", InFile);
                        }
                        else if (providerPaths.Count == 0)
                        {
                            errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, "WebCmdletInFileNoPathResolvedException", InFile);
                        }
                        else
                        {
                            if (Directory.Exists(providerPaths[0]))
                            {
                                errorRecord = GetValidationError(WebCmdletStrings.DirectoryPathSpecified, "WebCmdletInFileNotFilePathException", InFile);
                            }

                            _originalFilePath = InFile;
                            InFile = providerPaths[0];
                        }
                    }
                }
                catch (ItemNotFoundException pathNotFound)
                {
                    errorRecord = new ErrorRecord(pathNotFound.ErrorRecord, pathNotFound);
                }
                catch (ProviderNotFoundException providerNotFound)
                {
                    errorRecord = new ErrorRecord(providerNotFound.ErrorRecord, providerNotFound);
                }
                catch (System.Management.Automation.DriveNotFoundException driveNotFound)
                {
                    errorRecord = new ErrorRecord(driveNotFound.ErrorRecord, driveNotFound);
                }

                if (errorRecord is not null)
                {
                    ThrowTerminatingError(errorRecord);
                }
            }

            // Output ??
            if (PassThru.IsPresent && OutFile is null)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(PassThru));
                ThrowTerminatingError(error);
            }

            // Resume requires OutFile.
            if (Resume.IsPresent && OutFile is null)
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(Resume));
                ThrowTerminatingError(error);
            }

            _qualifiedOutFile = ShouldSaveToOutFile ? QualifiedOutFile : null;

            // OutFile must not be a directory to use Resume.
            if (Resume.IsPresent && Directory.Exists(_qualifiedOutFile))
            {
                ErrorRecord error = GetValidationError(WebCmdletStrings.ResumeNotFilePath, "WebCmdletResumeNotFilePathException", _qualifiedOutFile);
                ThrowTerminatingError(error);
            }
        }

        internal virtual void PrepareSession()
        {
            // Make sure we have a valid WebRequestSession object to work with
            WebSession ??= new WebRequestSession();

            if (SessionVariable is not null)
            {
                // Save the session back to the PS environment if requested
                PSVariableIntrinsics vi = SessionState.PSVariable;
                vi.Set(SessionVariable, WebSession);
            }

            // Handle credentials
            if (Credential is not null && Authentication == WebAuthenticationType.None)
            {
                // Get the relevant NetworkCredential
                NetworkCredential netCred = Credential.GetNetworkCredential();
                WebSession.Credentials = netCred;

                // Supplying a credential overrides the UseDefaultCredentials setting
                WebSession.UseDefaultCredentials = false;
            }
            else if ((Credential is not null || Token is not null) && Authentication != WebAuthenticationType.None)
            {
                ProcessAuthentication();
            }
            else if (UseDefaultCredentials)
            {
                WebSession.UseDefaultCredentials = true;
            }

            if (CertificateThumbprint is not null)
            {
                using X509Store store = new(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
                X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false);
                if (tbCollection.Count == 0)
                {
                    throw new CryptographicException(WebCmdletStrings.ThumbprintNotFound);
                }

                foreach (X509Certificate2 tbCert in tbCollection)
                {
                    X509Certificate certificate = (X509Certificate)tbCert;
                    WebSession.AddCertificate(certificate);
                }
            }

            if (Certificate is not null)
            {
                WebSession.AddCertificate(Certificate);
            }

            // Handle the user agent
            if (UserAgent is not null)
            {
                // Store the UserAgent string
                WebSession.UserAgent = UserAgent;
            }

            // Proxy and NoProxy parameters are mutually exclusive.
            // If NoProxy is provided, WebSession will turn off the proxy
            // and if Proxy is provided NoProxy will be turned off.
            if (NoProxy.IsPresent)
            {
                WebSession.NoProxy = true;
            }
            else
            {
                if (Proxy is not null)
                {
                    WebProxy webProxy = new(Proxy);
                    webProxy.BypassProxyOnLocal = false;
                    if (ProxyCredential is not null)
                    {
                        webProxy.Credentials = ProxyCredential.GetNetworkCredential();
                    }
                    else
                    {
                        webProxy.UseDefaultCredentials = ProxyUseDefaultCredentials;
                    }

                    // We don't want to update the WebSession unless the proxies are different
                    // as that will require us to create a new HttpClientHandler and lose connection
                    // persistence.
                    if (!webProxy.Equals(WebSession.Proxy))
                    {
                        WebSession.Proxy = webProxy;
                    }
                }
            }

            if (MyInvocation.BoundParameters.ContainsKey(nameof(SslProtocol)))
            {
                WebSession.SslProtocol = SslProtocol;
            }

            if (MaximumRedirection > -1)
            {
                WebSession.MaximumRedirection = MaximumRedirection;
            }

            WebSession.UnixSocket = UnixSocket;

            WebSession.SkipCertificateCheck = SkipCertificateCheck.IsPresent;

            // Store the other supplied headers
            if (Headers is not null)
            {
                foreach (string key in Headers.Keys)
                {
                    object value = Headers[key];

                    // null is not valid value for header.
                    // We silently ignore header if value is null.
                    if (value is not null)
                    {
                        // Add the header value (or overwrite it if already present).
                        WebSession.Headers[key] = value.ToString();
                    }
                }
            }

            if (MaximumRetryCount > 0)
            {
                WebSession.MaximumRetryCount = MaximumRetryCount;

                // Only set retry interval if retry count is set.
                WebSession.RetryIntervalInSeconds = RetryIntervalSec;
            }

            WebSession.ConnectionTimeout = ConvertTimeoutSecondsToTimeSpan(ConnectionTimeoutSeconds);
        }

        internal virtual HttpClient GetHttpClient(bool handleRedirect)
        {
            HttpClient client = WebSession.GetHttpClient(handleRedirect, out bool clientWasReset);

            if (clientWasReset)
            {
                WriteVerbose(WebCmdletStrings.WebSessionConnectionRecreated);
            }

            return client;
        }

        internal virtual HttpRequestMessage GetRequest(Uri uri)
        {
            Uri requestUri = PrepareUri(uri);
            HttpMethod httpMethod = string.IsNullOrEmpty(CustomMethod) ? GetHttpMethod(Method) : new HttpMethod(CustomMethod);

            // Create the base WebRequest object
            HttpRequestMessage request = new(httpMethod, requestUri);

            if (HttpVersion is not null)
            {
                request.Version = HttpVersion;
            }

            // Pull in session data
            if (WebSession.Headers.Count > 0)
            {
                WebSession.ContentHeaders.Clear();
                foreach (var entry in WebSession.Headers)
                {
                    if (HttpKnownHeaderNames.ContentHeaders.Contains(entry.Key))
                    {
                        WebSession.ContentHeaders.Add(entry.Key, entry.Value);
                    }
                    else
                    {
                        if (SkipHeaderValidation)
                        {
                            request.Headers.TryAddWithoutValidation(entry.Key, entry.Value);
                        }
                        else
                        {
                            request.Headers.Add(entry.Key, entry.Value);
                        }
                    }
                }
            }

            // Set 'Transfer-Encoding: chunked' if 'Transfer-Encoding' is specified
            if (WebSession.Headers.ContainsKey(HttpKnownHeaderNames.TransferEncoding))
            {
                request.Headers.TransferEncodingChunked = true;
            }

            // Set 'User-Agent' if WebSession.Headers doesn't already contain it
            if (WebSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out string userAgent))
            {
                WebSession.UserAgent = userAgent;
            }
            else
            {
                if (SkipHeaderValidation)
                {
                    request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.UserAgent, WebSession.UserAgent);
                }
                else
                {
                    request.Headers.Add(HttpKnownHeaderNames.UserAgent, WebSession.UserAgent);
                }
            }

            // Set 'Keep-Alive' to false. This means set the Connection to 'Close'.
            if (DisableKeepAlive)
            {
                request.Headers.Add(HttpKnownHeaderNames.Connection, "Close");
            }

            // Set 'Transfer-Encoding'
            if (TransferEncoding is not null)
            {
                request.Headers.TransferEncodingChunked = true;
                TransferCodingHeaderValue headerValue = new(TransferEncoding);
                if (!request.Headers.TransferEncoding.Contains(headerValue))
                {
                    request.Headers.TransferEncoding.Add(headerValue);
                }
            }

            // If the file to resume downloading exists, create the Range request header using the file size.
            // If not, create a Range to request the entire file.
            if (Resume.IsPresent)
            {
                FileInfo fileInfo = new(QualifiedOutFile);

                if (fileInfo.Exists)
                {
                    request.Headers.Range = new RangeHeaderValue(fileInfo.Length, null);
                    _resumeFileSize = fileInfo.Length;
                }
                else
                {
                    request.Headers.Range = new RangeHeaderValue(0, null);
                }
            }

            return request;
        }

        internal virtual void FillRequestStream(HttpRequestMessage request)
        {
            ArgumentNullException.ThrowIfNull(request);

            // Set the request content type
            if (ContentType is not null)
            {
                WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType;
            }
            else if (request.Method == HttpMethod.Post)
            {
                // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST
                WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out string contentType);
                if (string.IsNullOrEmpty(contentType))
                {
                    WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = "application/x-www-form-urlencoded";
                }
            }

            if (Form is not null)
            {
                MultipartFormDataContent formData = new();
                foreach (DictionaryEntry formEntry in Form)
                {
                    // AddMultipartContent will handle PSObject unwrapping, Object type determination and enumerateing top level IEnumerables.
                    AddMultipartContent(fieldName: formEntry.Key, fieldValue: formEntry.Value, formData: formData, enumerate: true);
                }

                SetRequestContent(request, formData);
            }
            else if (Body is not null)
            {
                // Coerce body into a usable form
                // Make sure we're using the base object of the body, not the PSObject wrapper
                object content = Body is PSObject psBody ? psBody.BaseObject : Body;

                switch (content)
                {
                    case FormObject form:
                        SetRequestContent(request, form.Fields);
                        break;
                    case IDictionary dictionary when request.Method != HttpMethod.Get:
                        SetRequestContent(request, dictionary);
                        break;
                    case XmlNode xmlNode:
                        SetRequestContent(request, xmlNode);
                        break;
                    case Stream stream:
                        SetRequestContent(request, stream);
                        break;
                    case byte[] bytes:
                        SetRequestContent(request, bytes);
                        break;
                    case MultipartFormDataContent multipartFormDataContent:
                        SetRequestContent(request, multipartFormDataContent);
                        break;
                    default:
                        SetRequestContent(request, (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture));
                        break;
                }
            }
            else if (InFile is not null)
            {
                // Copy InFile data
                try
                {
                    // Open the input file
                    SetRequestContent(request, new FileStream(InFile, FileMode.Open, FileAccess.Read, FileShare.Read));
                }
                catch (UnauthorizedAccessException)
                {
                    string msg = string.Format(CultureInfo.InvariantCulture, WebCmdletStrings.AccessDenied, _originalFilePath);

                    throw new UnauthorizedAccessException(msg);
                }
            }

            // For other methods like Put where empty content has meaning, we need to fill in the content
            if (request.Content is null)
            {
                // If this is a Get request and there is no content, then don't fill in the content as empty content gets rejected by some web services per RFC7230
                if (request.Method == HttpMethod.Get && ContentType is null)
                {
                    return;
                }

                request.Content = new StringContent(string.Empty);
                request.Content.Headers.Clear();
            }

            foreach (KeyValuePair<string, string> entry in WebSession.ContentHeaders)
            {
                if (!string.IsNullOrWhiteSpace(entry.Value))
                {
                    if (SkipHeaderValidation)
                    {
                        request.Content.Headers.TryAddWithoutValidation(entry.Key, entry.Value);
                    }
                    else
                    {
                        try
                        {
                            request.Content.Headers.Add(entry.Key, entry.Value);
                        }
                        catch (FormatException ex)
                        {
                            ValidationMetadataException outerEx = new(WebCmdletStrings.ContentTypeException, ex);
                            ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType);
                            ThrowTerminatingError(er);
                        }
                    }
                }
            }
        }

        internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool handleRedirect)
        {
            ArgumentNullException.ThrowIfNull(client);
            ArgumentNullException.ThrowIfNull(request);

            // Add 1 to account for the first request.
            int totalRequests = WebSession.MaximumRetryCount + 1;
            HttpRequestMessage currentRequest = request;
            HttpResponseMessage response = null;

            do
            {
                // Track the current URI being used by various requests and re-requests.
                Uri currentUri = currentRequest.RequestUri;

                _cancelToken = new CancellationTokenSource();
                try
                {
                    if (IsWriteVerboseEnabled())
                    {
                        WriteWebRequestVerboseInfo(currentRequest);
                    }

                    if (IsWriteDebugEnabled())
                    {
                        WriteWebRequestDebugInfo(currentRequest);
                    }

                    // codeql[cs/ssrf] - This is expected Poweshell behavior where user inputted Uri is supported for the context of this method. The user assumes trust for the Uri and invocation is done on the user's machine, not a web application. If there is concern for remoting, they should use restricted remoting.
                    response = client.SendAsync(currentRequest, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult();

                    if (IsWriteVerboseEnabled())
                    {
                        WriteWebResponseVerboseInfo(response);
                    }

                    if (IsWriteDebugEnabled())
                    {
                        WriteWebResponseDebugInfo(response);
                    }
                }
                catch (TaskCanceledException ex)
                {
                    if (ex.InnerException is TimeoutException)
                    {
                        // HTTP Request timed out
                        ErrorRecord er = new(ex, "ConnectionTimeoutReached", ErrorCategory.OperationTimeout, null);
                        ThrowTerminatingError(er);
                    }
                    else
                    {
                        throw;
                    }

                }
                if (handleRedirect
                    && _maximumRedirection is not 0
                    && IsRedirectCode(response.StatusCode)
                    && response.Headers.Location is not null)
                {
                    _cancelToken.Cancel();
                    _cancelToken = null;

                    // If explicit count was provided, reduce it for this redirection.
                    if (_maximumRedirection > 0)
                    {
                        _maximumRedirection--;
                    }

                    // For selected redirects, GET must be used with the redirected Location.
                    if (RequestRequiresForceGet(response.StatusCode, currentRequest.Method) && !PreserveHttpMethodOnRedirect)
                    {
                        Method = WebRequestMethod.Get;
                        CustomMethod = string.Empty;
                    }

                    currentUri = new Uri(request.RequestUri, response.Headers.Location);

                    // Continue to handle redirection
                    using HttpRequestMessage redirectRequest = GetRequest(currentUri);
                    response.Dispose();
                    response = GetResponse(client, redirectRequest, handleRedirect);
                }

                // Request again without the Range header because the server indicated the range was not satisfiable.
                // This happens when the local file is larger than the remote file.
                // If the size of the remote file is the same as the local file, there is nothing to resume.
                if (Resume.IsPresent
                    && response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable
                    && (response.Content.Headers.ContentRange.HasLength
                    && response.Content.Headers.ContentRange.Length != _resumeFileSize))
                {
                    _cancelToken.Cancel();

                    WriteVerbose(WebCmdletStrings.WebMethodResumeFailedVerboseMsg);

                    // Disable the Resume switch so the subsequent calls to GetResponse() and FillRequestStream()
                    // are treated as a standard -OutFile request. This also disables appending local file.
                    Resume = new SwitchParameter(false);

                    using (HttpRequestMessage requestWithoutRange = GetRequest(currentUri))
                    {
                        FillRequestStream(requestWithoutRange);

                        response.Dispose();
                        response = GetResponse(client, requestWithoutRange, handleRedirect);
                    }
                }

                _resumeSuccess = response.StatusCode == HttpStatusCode.PartialContent;

                // When MaximumRetryCount is not specified, the totalRequests is 1.
                if (totalRequests > 1 && ShouldRetry(response.StatusCode))
                {
                    int retryIntervalInSeconds = WebSession.RetryIntervalInSeconds;

                    // If the status code is 429 get the retry interval from the Headers.
                    // Ignore broken header and its value.
                    if (response.StatusCode is HttpStatusCode.TooManyRequests && response.Headers.TryGetValues(HttpKnownHeaderNames.RetryAfter, out IEnumerable<string> retryAfter))
                    {
                        try
                        {
                            IEnumerator<string> enumerator = retryAfter.GetEnumerator();
                            if (enumerator.MoveNext())
                            {
                                retryIntervalInSeconds = Convert.ToInt32(enumerator.Current);
                            }
                        }
                        catch
                        {
                            // Ignore broken header.
                        }
                    }

                    string retryMessage = string.Format(
                        CultureInfo.CurrentCulture,
                        WebCmdletStrings.RetryVerboseMsg,
                        retryIntervalInSeconds,
                        response.StatusCode);

                    WriteVerbose(retryMessage);

                    _cancelToken = new CancellationTokenSource();
                    Task.Delay(retryIntervalInSeconds * 1000, _cancelToken.Token).GetAwaiter().GetResult();
                    _cancelToken.Cancel();
                    _cancelToken = null;

                    currentRequest.Dispose();
                    currentRequest = GetRequest(currentUri);
                    FillRequestStream(currentRequest);
                }

                totalRequests--;
            }
            while (totalRequests > 0 && !response.IsSuccessStatusCode);

            return response;
        }

        internal virtual void UpdateSession(HttpResponseMessage response)
        {
            ArgumentNullException.ThrowIfNull(response);
        }
        #endregion Virtual Methods

        #region Helper Methods
#nullable enable
        internal static TimeSpan ConvertTimeoutSecondsToTimeSpan(int timeout) => timeout > 0 ? TimeSpan.FromSeconds(timeout) : Timeout.InfiniteTimeSpan;

        private void WriteWebRequestVerboseInfo(HttpRequestMessage request)
        {
            try
            {
                // Typical Basic Example: 'WebRequest: v1.1 POST https://httpstat.us/200 with query length 6'
                StringBuilder verboseBuilder = new(128);

                // "Redact" the query string from verbose output, the details will be visible in Debug output
                string uriWithoutQuery = request.RequestUri?.GetLeftPart(UriPartial.Path) ?? string.Empty;
                verboseBuilder.Append($"WebRequest: v{request.Version} {request.Method} {uriWithoutQuery}");
                if (request.RequestUri?.Query is not null && request.RequestUri.Query.Length > 1)
                {
                    verboseBuilder.Append($" with query length {request.RequestUri.Query.Length - 1}");
                }

                string? requestContentType = ContentHelper.GetContentType(request);
                if (requestContentType is not null)
                {
                    verboseBuilder.Append($" with {requestContentType} payload");
                }

                long? requestContentLength = request.Content?.Headers?.ContentLength;
                if (requestContentLength is not null)
                {
                    verboseBuilder.Append($" with body size {ContentHelper.GetFriendlyContentLength(requestContentLength)}");
                }
                if (OutFile is not null)
                {
                    verboseBuilder.Append($" output to {QualifyFilePath(OutFile)}");
                }

                WriteVerbose(verboseBuilder.ToString().Trim());
            }
            catch (Exception ex)
            {
                // Just in case there are any edge cases we missed, we don't break workflows with an exception
                WriteVerbose($"Failed to Write WebRequest Verbose Info: {ex} {ex.StackTrace}");
            }
        }

        private void WriteWebRequestDebugInfo(HttpRequestMessage request)
        {
            try
            {
                // Typical basic example:
                // WebRequest Detail
                // ---QUERY
                // test = 5
                // --- HEADERS
                // User - Agent: Mozilla / 5.0, (Linux;Ubuntu 24.04.2 LTS;en - US), PowerShell / 7.6.0
                StringBuilder debugBuilder = new("WebRequest Detail" + Environment.NewLine, 512);

                if (!string.IsNullOrEmpty(request.RequestUri?.Query))
                {
                    debugBuilder.Append(DebugHeaderPrefix).AppendLine("QUERY");
                    string[] queryParams = request.RequestUri.Query.TrimStart('?').Split('&');
                    debugBuilder
                        .AppendJoin(Environment.NewLine, queryParams)
                        .AppendLine()
                        .AppendLine();
                }

                debugBuilder.Append(DebugHeaderPrefix).AppendLine("HEADERS");

                foreach (var headerSet in new HttpHeaders?[] { request.Headers, request.Content?.Headers })
                {
                    if (headerSet is null)
                    {
                        continue;
                    }

                    debugBuilder.AppendLine(headerSet.ToString());
                }

                if (request.Content is not null)
                {
                    debugBuilder
                    .Append(DebugHeaderPrefix).AppendLine("BODY")
                    .AppendLine(request.Content switch
                    {
                        StringContent stringContent => stringContent
                            .ReadAsStringAsync(_cancelToken.Token)
                            .GetAwaiter().GetResult(),
                        MultipartFormDataContent multipartContent => "=> Multipart Form Content"
                            + Environment.NewLine
                            + multipartContent.ReadAsStringAsync(_cancelToken.Token)
                            .GetAwaiter().GetResult(),
                        ByteArrayContent byteContent => InFile is not null
                            ? "[Binary content: "
                                + ContentHelper.GetFriendlyContentLength(byteContent.Headers.ContentLength)
                                + "]"
                            : byteContent.ReadAsStringAsync(_cancelToken.Token).GetAwaiter().GetResult(),
                        StreamContent streamContent =>
                            "[Stream content: " + ContentHelper.GetFriendlyContentLength(streamContent.Headers.ContentLength) + "]",
                        _ => "[Unknown content type]",
                    })
                    .AppendLine();
                }

                WriteDebug(debugBuilder.ToString().Trim());
            }
            catch (Exception ex)
            {
                // Just in case there are any edge cases we missed, we don't break workflows with an exception
                WriteVerbose($"Failed to Write WebRequest Debug Info: {ex} {ex.StackTrace}");
            }
        }

        private void WriteWebResponseVerboseInfo(HttpResponseMessage response)
        {
            try
            {
                // Typical basic example: WebResponse: 200 OK with text/plain payload body size 6 B (6 bytes)
                StringBuilder verboseBuilder = new(128);
                verboseBuilder.Append($"WebResponse: {(int)response.StatusCode} {response.ReasonPhrase ?? response.StatusCode.ToString()}");

                string? responseContentType = ContentHelper.GetContentType(response);
                if (responseContentType is not null)
                {
                    verboseBuilder.Append($" with {responseContentType} payload");
                }

                long? responseContentLength = response.Content?.Headers?.ContentLength;
                if (responseContentLength is not null)
                {
                    verboseBuilder.Append($" with body size {ContentHelper.GetFriendlyContentLength(responseContentLength)}");
                }

                WriteVerbose(verboseBuilder.ToString().Trim());
            }
            catch (Exception ex)
            {
                // Just in case there are any edge cases we missed, we don't break workflows with an exception
                WriteVerbose($"Failed to Write WebResponse Verbose Info: {ex} {ex.StackTrace}");
            }
        }

        private void WriteWebResponseDebugInfo(HttpResponseMessage response)
        {
            try
            {
                // Typical basic example
                // WebResponse Detail
                // --- HEADERS
                // Date: Fri, 09 May 2025 18:06:44 GMT
                // Server: Kestrel
                // Set-Cookie: ARRAffinity=ee0b467f95b53d8dcfe48aeeb4173f93cf819be6e4721f434341647f4695039d;Path=/;HttpOnly;Secure;Domain=httpstat.us, ARRAffinitySameSite=ee0b467f95b53d8dcfe48aeeb4173f93cf819be6e4721f434341647f4695039d;Path=/;HttpOnly;SameSite=None;Secure;Domain=httpstat.us
                // Strict-Transport-Security: max-age=2592000
                // Request-Context: appId=cid-v1:3548b0f5-7f75-492f-82bb-b6eb0e864e53
                // Content-Length: 6
                // Content-Type: text/plain
                // --- BODY
                // 200 OK
                StringBuilder debugBuilder = new("WebResponse Detail" + Environment.NewLine, 512);

                debugBuilder.Append(DebugHeaderPrefix).AppendLine("HEADERS");

                foreach (var headerSet in new HttpHeaders?[] { response.Headers, response.Content?.Headers })
                {
                    if (headerSet is null)
                    {
                        continue;
                    }

                    debugBuilder.AppendLine(headerSet.ToString());
                }

                if (response.Content is not null)
                {
                    debugBuilder.Append(DebugHeaderPrefix).AppendLine("BODY");

                    if (ContentHelper.IsTextBasedContentType(ContentHelper.GetContentType(response)))
                    {
                        debugBuilder.AppendLine(
                            response.Content.ReadAsStringAsync(_cancelToken.Token)
                            .GetAwaiter().GetResult());
                    }
                    else
                    {
                        string friendlyContentLength = ContentHelper.GetFriendlyContentLength(
                            response.Content?.Headers?.ContentLength);
                        debugBuilder.AppendLine($"[Binary content: {friendlyContentLength}]");
                    }
                }

                WriteDebug(debugBuilder.ToString().Trim());
            }
            catch (Exception ex)
            {
                // Just in case there are any edge cases we missed, we don't break workflows with an exception
                WriteVerbose($"Failed to Write WebResponse Debug Info: {ex} {ex.StackTrace}");
            }
        }

        private Uri PrepareUri(Uri uri)
        {
            uri = CheckProtocol(uri);

            // Before creating the web request,
            // preprocess Body if content is a dictionary and method is GET (set as query)
            LanguagePrimitives.TryConvertTo<IDictionary>(Body, out IDictionary bodyAsDictionary);
            if (bodyAsDictionary is not null && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get || CustomMethod == "GET"))
            {
                UriBuilder uriBuilder = new(uri);
                if (uriBuilder.Query is not null && uriBuilder.Query.Length > 1)
                {
                    uriBuilder.Query = string.Concat(uriBuilder.Query.AsSpan(1), "&", FormatDictionary(bodyAsDictionary));
                }
                else
                {
                    uriBuilder.Query = FormatDictionary(bodyAsDictionary);
                }

                uri = uriBuilder.Uri;

                // Set body to null to prevent later FillRequestStream
                Body = null;
            }

            return uri;
        }

        private static Uri CheckProtocol(Uri uri)
        {
            ArgumentNullException.ThrowIfNull(uri);

            return uri.IsAbsoluteUri ? uri : new Uri("http://" + uri.OriginalString);
        }
#nullable restore

        private string QualifyFilePath(string path) => PathUtils.ResolveFilePath(filePath: path, command: this, isLiteralPath: true);

        private static string FormatDictionary(IDictionary content)
        {
            ArgumentNullException.ThrowIfNull(content);

            StringBuilder bodyBuilder = new();
            foreach (string key in content.Keys)
            {
                if (bodyBuilder.Length > 0)
                {
                    bodyBuilder.Append('&');
                }

                object value = content[key];

                // URLEncode the key and value
                string encodedKey = WebUtility.UrlEncode(key);
                string encodedValue = value is null ? string.Empty : WebUtility.UrlEncode(value.ToString());

                bodyBuilder.Append($"{encodedKey}={encodedValue}");
            }

            return bodyBuilder.ToString();
        }

        private ErrorRecord GetValidationError(string msg, string errorId)
        {
            ValidationMetadataException ex = new(msg);
            return new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this);
        }

        private ErrorRecord GetValidationError(string msg, string errorId, params object[] args)
        {
            msg = string.Format(CultureInfo.InvariantCulture, msg, args);
            ValidationMetadataException ex = new(msg);
            return new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this);
        }

        private string GetBasicAuthorizationHeader()
        {
            string password = new NetworkCredential(string.Empty, Credential.Password).Password;
            string unencoded = string.Create(CultureInfo.InvariantCulture, $"{Credential.UserName}:{password}");
            byte[] bytes = Encoding.UTF8.GetBytes(unencoded);
            return string.Create(CultureInfo.InvariantCulture, $"Basic {Convert.ToBase64String(bytes)}");
        }

        private string GetBearerAuthorizationHeader()
        {
            return string.Create(CultureInfo.InvariantCulture, $"Bearer {new NetworkCredential(string.Empty, Token).Password}");
        }

        private void ProcessAuthentication()
        {
            if (Authentication == WebAuthenticationType.Basic)
            {
                WebSession.Headers["Authorization"] = GetBasicAuthorizationHeader();
            }
            else if (Authentication == WebAuthenticationType.Bearer || Authentication == WebAuthenticationType.OAuth)
            {
                WebSession.Headers["Authorization"] = GetBearerAuthorizationHeader();
            }
            else
            {
                Diagnostics.Assert(false, string.Create(CultureInfo.InvariantCulture, $"Unrecognized Authentication value: {Authentication}"));
            }
        }

        private bool IsPersistentSession() => MyInvocation.BoundParameters.ContainsKey(nameof(WebSession)) || MyInvocation.BoundParameters.ContainsKey(nameof(SessionVariable));

        /// <summary>
        /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream.
        /// </summary>
        /// <param name="request">The WebRequest who's content is to be set.</param>
        /// <param name="content">A byte array containing the content data.</param>
        /// <remarks>
        /// Because this function sets the request's ContentLength property and writes content data into the request's stream,
        /// it should be called one time maximum on a given request.
        /// </remarks>
        internal void SetRequestContent(HttpRequestMessage request, byte[] content)
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(content);

            request.Content = new ByteArrayContent(content);
        }

        /// <summary>
        /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream.
        /// </summary>
        /// <param name="request">The WebRequest who's content is to be set.</param>
        /// <param name="content">A String object containing the content data.</param>
        /// <remarks>
        /// Because this function sets the request's ContentLength property and writes content data into the request's stream,
        /// it should be called one time maximum on a given request.
        /// </remarks>
        internal void SetRequestContent(HttpRequestMessage request, string content)
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(content);

            Encoding encoding = null;

            if (WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out string contentType) && contentType is not null)
            {
                // If Content-Type contains the encoding format (as CharSet), use this encoding format
                // to encode the Body of the WebRequest sent to the server. Default Encoding format
                // would be used if Charset is not supplied in the Content-Type property.
                try
                {
                    MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(contentType);
                    if (!string.IsNullOrEmpty(mediaTypeHeaderValue.CharSet))
                    {
                        encoding = Encoding.GetEncoding(mediaTypeHeaderValue.CharSet);
                    }
                }
                catch (Exception ex) when (ex is FormatException || ex is ArgumentException)
                {
                    if (!SkipHeaderValidation)
                    {
                        ValidationMetadataException outerEx = new(WebCmdletStrings.ContentTypeException, ex);
                        ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, contentType);
                        ThrowTerminatingError(er);
                    }
                }
            }

            byte[] bytes = StreamHelper.EncodeToBytes(content, encoding);
            request.Content = new ByteArrayContent(bytes);
        }

        internal void SetRequestContent(HttpRequestMessage request, XmlNode xmlNode)
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(xmlNode);

            byte[] bytes = null;
            XmlDocument doc = xmlNode as XmlDocument;
            if (doc?.FirstChild is XmlDeclaration decl && !string.IsNullOrEmpty(decl.Encoding))
            {
                Encoding encoding = Encoding.GetEncoding(decl.Encoding);
                bytes = StreamHelper.EncodeToBytes(doc.OuterXml, encoding);
            }
            else
            {
                bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml, encoding: null);
            }

            request.Content = new ByteArrayContent(bytes);
        }

        /// <summary>
        /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream.
        /// </summary>
        /// <param name="request">The WebRequest who's content is to be set.</param>
        /// <param name="contentStream">A Stream object containing the content data.</param>
        /// <remarks>
        /// Because this function sets the request's ContentLength property and writes content data into the request's stream,
        /// it should be called one time maximum on a given request.
        /// </remarks>
        internal void SetRequestContent(HttpRequestMessage request, Stream contentStream)
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(contentStream);

            request.Content = new StreamContent(contentStream);
        }

        /// <summary>
        /// Sets the ContentLength property of the request and writes the ContentLength property of the request and writes the specified content to the request's RequestStream.
        /// </summary>
        /// <param name="request">The WebRequest who's content is to be set.</param>
        /// <param name="multipartContent">A MultipartFormDataContent object containing multipart/form-data content.</param>
        /// <remarks>
        /// Because this function sets the request's ContentLength property and writes content data into the request's stream,
        /// it should be called one time maximum on a given request.
        /// </remarks>
        internal void SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent)
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(multipartContent);

            // Content headers will be set by MultipartFormDataContent which will throw unless we clear them first
            WebSession.ContentHeaders.Clear();

            request.Content = multipartContent;
        }

        internal void SetRequestContent(HttpRequestMessage request, IDictionary content)
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(content);

            string body = FormatDictionary(content);
            SetRequestContent(request, body);
        }

        internal void ParseLinkHeader(HttpResponseMessage response)
        {
            Uri requestUri = response.RequestMessage.RequestUri;
            if (_relationLink is null)
            {
                // Must ignore the case of relation links. See RFC 8288 (https://tools.ietf.org/html/rfc8288)
                _relationLink = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            }
            else
            {
                _relationLink.Clear();
            }

            // We only support the URL in angle brackets and `rel`, other attributes are ignored
            // user can still parse it themselves via the Headers property
            const string Pattern = "<(?<url>.*?)>;\\s*rel=(?<quoted>\")?(?<rel>(?(quoted).*?|[^,;]*))(?(quoted)\")";
            if (response.Headers.TryGetValues("Link", out IEnumerable<string> links))
            {
                foreach (string linkHeader in links)
                {
                    MatchCollection matchCollection = Regex.Matches(linkHeader, Pattern);
                    foreach (Match match in matchCollection)
                    {
                        if (match.Success)
                        {
                            string url = match.Groups["url"].Value;
                            string rel = match.Groups["rel"].Value;
                            if (url != string.Empty && rel != string.Empty && !_relationLink.ContainsKey(rel))
                            {
                                Uri absoluteUri = new(requestUri, url);
                                _relationLink.Add(rel, absoluteUri.AbsoluteUri);
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Adds content to a <see cref="MultipartFormDataContent"/>. Object type detection is used to determine if the value is string, File, or Collection.
        /// </summary>
        /// <param name="fieldName">The Field Name to use.</param>
        /// <param name="fieldValue">The Field Value to use.</param>
        /// <param name="formData">The <see cref="MultipartFormDataContent"/> to update.</param>
        /// <param name="enumerate">If true, collection types in <paramref name="fieldValue"/> will be enumerated. If false, collections will be treated as single value.</param>
        private static void AddMultipartContent(object fieldName, object fieldValue, MultipartFormDataContent formData, bool enumerate)
        {
            ArgumentNullException.ThrowIfNull(formData);

            // It is possible that the dictionary keys or values are PSObject wrapped depending on how the dictionary is defined and assigned.
            // Before processing the field name and value we need to ensure we are working with the base objects and not the PSObject wrappers.

            // Unwrap fieldName PSObjects
            if (fieldName is PSObject namePSObject)
            {
                fieldName = namePSObject.BaseObject;
            }

            // Unwrap fieldValue PSObjects
            if (fieldValue is PSObject valuePSObject)
            {
                fieldValue = valuePSObject.BaseObject;
            }

            // Treat a single FileInfo as a FileContent
            if (fieldValue is FileInfo file)
            {
                formData.Add(GetMultipartFileContent(fieldName: fieldName, file: file));
                return;
            }

            // Treat Strings and other single values as a StringContent.
            // If enumeration is false, also treat IEnumerables as StringContents.
            // String implements IEnumerable so the explicit check is required.
            if (!enumerate || fieldValue is string || fieldValue is not IEnumerable)
            {
                formData.Add(GetMultipartStringContent(fieldName: fieldName, fieldValue: fieldValue));
                return;
            }

            // Treat the value as a collection and enumerate it if enumeration is true
            if (enumerate && fieldValue is IEnumerable items)
            {
                foreach (object item in items)
                {
                    // Recurse, but do not enumerate the next level. IEnumerables will be treated as single values.
                    AddMultipartContent(fieldName: fieldName, fieldValue: item, formData: formData, enumerate: false);
                }
            }
        }

        /// <summary>
        /// Gets a <see cref="StringContent"/> from the supplied field name and field value. Uses <see cref="LanguagePrimitives.ConvertTo{T}(object)"/> to convert the objects to strings.
        /// </summary>
        /// <param name="fieldName">The Field Name to use for the <see cref="StringContent"/></param>
        /// <param name="fieldValue">The Field Value to use for the <see cref="StringContent"/></param>
        private static StringContent GetMultipartStringContent(object fieldName, object fieldValue)
        {
            ContentDispositionHeaderValue contentDisposition = new("form-data");
            contentDisposition.Name = LanguagePrimitives.ConvertTo<string>(fieldName);

            // codeql[cs/information-exposure-through-exception] - PowerShell is an on-premise product, meaning local users would already have access to the binaries and stack traces. Therefore, the information would not be exposed in the same way it would be for an ASP .NET service.
            StringContent result = new(LanguagePrimitives.ConvertTo<string>(fieldValue));
            result.Headers.ContentDisposition = contentDisposition;

            return result;
        }

        /// <summary>
        /// Gets a <see cref="StreamContent"/> from the supplied field name and <see cref="Stream"/>. Uses <see cref="LanguagePrimitives.ConvertTo{T}(object)"/> to convert the fieldname to a string.
        /// </summary>
        /// <param name="fieldName">The Field Name to use for the <see cref="StreamContent"/></param>
        /// <param name="stream">The <see cref="Stream"/> to use for the <see cref="StreamContent"/></param>
        private static StreamContent GetMultipartStreamContent(object fieldName, Stream stream)
        {
            ContentDispositionHeaderValue contentDisposition = new("form-data");
            contentDisposition.Name = LanguagePrimitives.ConvertTo<string>(fieldName);

            StreamContent result = new(stream);
            result.Headers.ContentDisposition = contentDisposition;
            result.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            return result;
        }

        /// <summary>
        /// Gets a <see cref="StreamContent"/> from the supplied field name and file. Calls <see cref="GetMultipartStreamContent(object, Stream)"/> to create the <see cref="StreamContent"/> and then sets the file name.
        /// </summary>
        /// <param name="fieldName">The Field Name to use for the <see cref="StreamContent"/></param>
        /// <param name="file">The file to use for the <see cref="StreamContent"/></param>
        private static StreamContent GetMultipartFileContent(object fieldName, FileInfo file)
        {
            StreamContent result = GetMultipartStreamContent(fieldName: fieldName, stream: new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read));

            result.Headers.ContentDisposition.FileName = file.Name;
            result.Headers.ContentDisposition.FileNameStar = file.Name;

            return result;
        }

        private static string FormatErrorMessage(string error, string contentType)
        {
            string formattedError = null;

            try
            {
                if (ContentHelper.IsXml(contentType))
                {
                    XmlDocument doc = new();
                    doc.LoadXml(error);

                    XmlWriterSettings settings = new XmlWriterSettings
                    {
                        Indent = true,
                        NewLineOnAttributes = true,
                        OmitXmlDeclaration = true
                    };

                    if (doc.FirstChild is XmlDeclaration decl)
                    {
                        settings.Encoding = Encoding.GetEncoding(decl.Encoding);
                    }

                    StringBuilder stringBuilder = new();
                    using XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, settings);
                    doc.Save(xmlWriter);
                    string xmlString = stringBuilder.ToString();

                    formattedError = Environment.NewLine + xmlString;
                }
                else if (ContentHelper.IsJson(contentType))
                {
                    JsonNode jsonNode = JsonNode.Parse(error);
                    JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true };
                    string jsonString = jsonNode.ToJsonString(options);

                    formattedError = Environment.NewLine + jsonString;
                }
            }
            catch
            {
                // Ignore errors
            }

            if (string.IsNullOrEmpty(formattedError))
            {
                // Remove HTML tags making it easier to read
                formattedError = Regex.Replace(error, "<[^>]*>", string.Empty);
            }

            return formattedError;
        }

        // Returns true if the status code is one of the supported redirection codes.
        private static bool IsRedirectCode(HttpStatusCode statusCode) => statusCode switch
        {
            HttpStatusCode.Found
            or HttpStatusCode.Moved
            or HttpStatusCode.MultipleChoices
            or HttpStatusCode.PermanentRedirect
            or HttpStatusCode.SeeOther
            or HttpStatusCode.TemporaryRedirect => true,
            _ => false
        };

        // Returns true if the status code is a redirection code and the action requires switching to GET on redirection.
        // See https://learn.microsoft.com/en-us/dotnet/api/system.net.httpstatuscode
        private static bool RequestRequiresForceGet(HttpStatusCode statusCode, HttpMethod requestMethod) => statusCode switch
        {
            HttpStatusCode.Found
            or HttpStatusCode.Moved
            or HttpStatusCode.MultipleChoices => requestMethod == HttpMethod.Post,
            HttpStatusCode.SeeOther => requestMethod != HttpMethod.Get && requestMethod != HttpMethod.Head,
            _ => false
        };

        // Returns true if the status code shows a server or client error and MaximumRetryCount > 0
        private static bool ShouldRetry(HttpStatusCode statusCode) => (int)statusCode switch
        {
            304 or (>= 400 and <= 599) => true,
            _ => false
        };

        private static HttpMethod GetHttpMethod(WebRequestMethod method) => method switch
        {
            WebRequestMethod.Default or WebRequestMethod.Get => HttpMethod.Get,
            WebRequestMethod.Delete => HttpMethod.Delete,
            WebRequestMethod.Head => HttpMethod.Head,
            WebRequestMethod.Patch => HttpMethod.Patch,
            WebRequestMethod.Post => HttpMethod.Post,
            WebRequestMethod.Put => HttpMethod.Put,
            WebRequestMethod.Options => HttpMethod.Options,
            WebRequestMethod.Trace => HttpMethod.Trace,
            _ => new HttpMethod(method.ToString().ToUpperInvariant())
        };

        #endregion Helper Methods
    }

    /// <summary>
    /// Exception class for webcmdlets to enable returning HTTP error response.
    /// </summary>
    public sealed class HttpResponseException : HttpRequestException
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpResponseException"/> class.
        /// </summary>
        /// <param name="message">Message for the exception.</param>
        /// <param name="response">Response from the HTTP server.</param>
        public HttpResponseException(string message, HttpResponseMessage response) : base(message, inner: null, response.StatusCode)
        {
            Response = response;
        }

        /// <summary>
        /// HTTP error response.
        /// </summary>
        public HttpResponseMessage Response { get; }
    }
}