diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs
index 59cc69c8346..6039c6064a9 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs
@@ -25,32 +25,6 @@ public class InvokeRestMethodCommand : WebRequestPSCmdlet
{
#region Parameters
- ///
- /// Gets or sets the parameter Method.
- ///
- [Parameter(ParameterSetName = "StandardMethod")]
- [Parameter(ParameterSetName = "StandardMethodNoProxy")]
- public override WebRequestMethod Method
- {
- get => base.Method;
-
- set => base.Method = value;
- }
-
- ///
- /// Gets or sets the parameter CustomMethod.
- ///
- [Parameter(Mandatory = true, ParameterSetName = "CustomMethod")]
- [Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")]
- [Alias("CM")]
- [ValidateNotNullOrEmpty]
- public override string CustomMethod
- {
- get => base.CustomMethod;
-
- set => base.CustomMethod = value.ToUpperInvariant();
- }
-
///
/// Enable automatic following of rel links.
///
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs
index 3dcf289761a..ed84cb59661 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs
@@ -60,7 +60,7 @@ public enum WebSslProtocol
///
/// No SSL protocol will be set and the system defaults will be used.
///
- Default = 0,
+ Default = SslProtocols.None,
///
/// Specifies the TLS 1.0 is obsolete. Using this value now defaults to TLS 1.2.
@@ -433,13 +433,7 @@ internal virtual void ValidateParameters()
ThrowTerminatingError(error);
}
- if (!AllowUnencryptedAuthentication && Authentication != WebAuthenticationType.None && Uri.Scheme != "https")
- {
- ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException");
- ThrowTerminatingError(error);
- }
-
- if (!AllowUnencryptedAuthentication && (Credential is not null || UseDefaultCredentials) && Uri.Scheme != "https")
+ if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None || Credential is not null || UseDefaultCredentials) && Uri.Scheme != "https")
{
ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException");
ThrowTerminatingError(error);
@@ -486,12 +480,11 @@ internal virtual void ValidateParameters()
// Validate InFile path
if (InFile is not null)
{
- ProviderInfo provider = null;
ErrorRecord errorRecord = null;
try
{
- Collection providerPaths = GetResolvedProviderPathFromPSPath(InFile, out provider);
+ Collection providerPaths = GetResolvedProviderPathFromPSPath(InFile, out ProviderInfo provider);
if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
{
@@ -688,10 +681,9 @@ private Uri PrepareUri(Uri uri)
{
uri = CheckProtocol(uri);
- // before creating the web request,
+ // Before creating the web request,
// preprocess Body if content is a dictionary and method is GET (set as query)
- IDictionary bodyAsDictionary;
- LanguagePrimitives.TryConvertTo(Body, out bodyAsDictionary);
+ LanguagePrimitives.TryConvertTo(Body, out IDictionary bodyAsDictionary);
if (bodyAsDictionary is not null && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get || CustomMethod == "GET"))
{
UriBuilder uriBuilder = new(uri);
@@ -970,16 +962,8 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect)
HttpClient httpClient = new(handler);
- // check timeout setting (in seconds instead of milliseconds as in HttpWebRequest)
- if (TimeoutSec == 0)
- {
- // A zero timeout means infinite
- httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
- }
- else if (TimeoutSec > 0)
- {
- httpClient.Timeout = new TimeSpan(0, 0, TimeoutSec);
- }
+ // Check timeout setting (in seconds instead of milliseconds as in HttpWebRequest)
+ httpClient.Timeout = TimeoutSec is 0 ? TimeSpan.FromMilliseconds(Timeout.Infinite) : new TimeSpan(0, 0, TimeoutSec);
return httpClient;
}
@@ -1028,8 +1012,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri)
}
// Set 'User-Agent' if WebSession.Headers doesn't already contain it
- string userAgent = null;
- if (WebSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out userAgent))
+ if (WebSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out string userAgent))
{
WebSession.UserAgent = userAgent;
}
@@ -1095,8 +1078,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request)
else if (request.Method == HttpMethod.Post)
{
// Win8:545310 Invoke-WebRequest does not properly set MIME type for POST
- string contentType = null;
- WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out contentType);
+ WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out string contentType);
if (string.IsNullOrEmpty(contentType))
{
WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = "application/x-www-form-urlencoded";
@@ -1283,7 +1265,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM
_cancelToken.Cancel();
_cancelToken = null;
- // if explicit count was provided, reduce it for this redirection.
+ // If explicit count was provided, reduce it for this redirection.
if (WebSession.MaximumRedirection > 0)
{
WebSession.MaximumRedirection--;
@@ -1444,7 +1426,9 @@ protected override void ProcessRecord()
{
long requestContentLength = 0;
if (request.Content is not null)
+ {
requestContentLength = request.Content.Headers.ContentLength.Value;
+ }
string reqVerboseMsg = string.Format(
CultureInfo.CurrentCulture,
@@ -1644,16 +1628,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content)
encoding = Encoding.GetEncoding(mediaTypeHeaderValue.CharSet);
}
}
- catch (FormatException ex)
- {
- if (!SkipHeaderValidation)
- {
- var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex);
- ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType);
- ThrowTerminatingError(er);
- }
- }
- catch (ArgumentException ex)
+ catch (Exception ex) when (ex is FormatException || ex is ArgumentException)
{
if (!SkipHeaderValidation)
{
@@ -1690,7 +1665,7 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode)
}
else
{
- bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml);
+ bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml, encoding: null);
}
var byteArrayContent = new ByteArrayContent(bytes);
@@ -1767,8 +1742,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr
// 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 = "<(?.*?)>;\\s*rel=(?\")?(?(?(quoted).*?|[^,;]*))(?(quoted)\")";
- IEnumerable links;
- if (response.Headers.TryGetValues("Link", out links))
+ if (response.Headers.TryGetValues("Link", out IEnumerable links))
{
foreach (string linkHeader in links)
{
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs
index afa17912244..9d0f4a93797 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs
@@ -38,8 +38,7 @@ internal class WebResponseContentMemoryStream : MemoryStream
///
/// Owner cmdlet if any.
/// Expected download size in Bytes.
- internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet, long? contentLength)
- : base(initialCapacity)
+ internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet, long? contentLength) : base(initialCapacity)
{
this._contentLength = contentLength;
_originalStreamToProxy = stream;
@@ -49,43 +48,15 @@ internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdl
///
///
- public override bool CanRead
- {
- get
- {
- return true;
- }
- }
-
- ///
- ///
- public override bool CanSeek
- {
- get
- {
- return true;
- }
- }
+ public override bool CanRead => true;
///
///
- public override bool CanTimeout
- {
- get
- {
- return base.CanTimeout;
- }
- }
+ public override bool CanSeek => true;
///
///
- public override bool CanWrite
- {
- get
- {
- return true;
- }
- }
+ public override bool CanWrite => true;
///
///
@@ -215,7 +186,10 @@ protected override void Dispose(bool disposing)
///
private void Initialize()
{
- if (_isInitialized) { return; }
+ if (_isInitialized)
+ {
+ return;
+ }
_isInitialized = true;
try
@@ -226,7 +200,7 @@ private void Initialize()
string totalDownloadSize = _contentLength is null ? "???" : Utils.DisplayHumanReadableFileSize((long)_contentLength);
for (int read = 1; read > 0; totalRead += read)
{
- if (_ownerCmdlet != null)
+ if (_ownerCmdlet is not null)
{
record.StatusDescription = StringUtil.Format(
WebCmdletStrings.ReadResponseProgressStatus,
@@ -254,14 +228,14 @@ private void Initialize()
}
}
- if (_ownerCmdlet != null)
+ if (_ownerCmdlet is not null)
{
record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseComplete, totalRead);
record.RecordType = ProgressRecordType.Completed;
_ownerCmdlet.WriteProgress(record);
}
- // make sure the length is set appropriately
+ // Make sure the length is set appropriately
base.SetLength(totalRead);
base.Seek(0, SeekOrigin.Begin);
}
@@ -281,7 +255,7 @@ internal static class StreamHelper
internal const int ChunkSize = 10000;
- // just picked a random number
+ // Just picked a random number
internal const int ActivityId = 174593042;
#endregion Constants
@@ -377,8 +351,6 @@ private static string StreamToString(Stream stream, Encoding encoding)
bool completed = false;
int byteIndex = 0;
- int bytesUsed;
- int charsUsed;
while (!completed)
{
@@ -386,7 +358,7 @@ private static string StreamToString(Stream stream, Encoding encoding)
bool flush = (bytesRead == 0);
decoder.Convert(bytes, byteIndex, bytesRead - byteIndex,
chars, 0, useBufferSize, flush,
- out bytesUsed, out charsUsed, out completed);
+ out int bytesUsed, out int charsUsed, out completed);
// The conversion produced the number of characters indicated by charsUsed. Write that number
// of characters to our result buffer
@@ -447,7 +419,7 @@ internal static bool TryGetEncoding(string characterSet, out Encoding encoding)
internal static string DecodeStream(Stream stream, ref Encoding encoding)
{
bool isDefaultEncoding = false;
- if (encoding == null)
+ if (encoding is null)
{
// Use the default encoding if one wasn't provided
encoding = ContentHelper.GetDefaultEncoding();
@@ -459,7 +431,7 @@ internal static string DecodeStream(Stream stream, ref Encoding encoding)
{
do
{
- // check for a charset attribute on the meta element to override the default
+ // Check for a charset attribute on the meta element to override the default
// we only look within the first 1k characters as the meta tag is in the head
// tag which is at the start of the document
Match match = s_metaexp.Match(content.Substring(0, Math.Min(content.Length, 1024)));
@@ -472,7 +444,8 @@ internal static string DecodeStream(Stream stream, ref Encoding encoding)
{
stream.Seek(0, SeekOrigin.Begin);
content = StreamToString(stream, localEncoding);
- // report the encoding used.
+
+ // Report the encoding used.
encoding = localEncoding;
}
}
@@ -484,23 +457,13 @@ internal static string DecodeStream(Stream stream, ref Encoding encoding)
internal static byte[] EncodeToBytes(string str, Encoding encoding)
{
- // just use the default encoding if one wasn't provided
+ // Just use the default encoding if one wasn't provided
encoding ??= ContentHelper.GetDefaultEncoding();
return encoding.GetBytes(str);
}
- internal static byte[] EncodeToBytes(string str)
- {
- return EncodeToBytes(str, null);
- }
-
- internal static Stream GetResponseStream(HttpResponseMessage response)
- {
- Stream responseStream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
-
- return responseStream;
- }
+ internal static Stream GetResponseStream(HttpResponseMessage response) => response.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
#endregion Static Methods
}