From e8d472b65bf25f831a1054a1bf8552725a22fff3 Mon Sep 17 00:00:00 2001 From: Ilya Date: Wed, 8 Jan 2020 01:25:30 +0500 Subject: [PATCH] Ignore headers with null values in web cmdlets (#11424) --- .../WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 11 +++++++++-- .../WebCmdlets.Tests.ps1 | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 4c5d3e8227..133ca142f4 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 @@ -663,8 +663,15 @@ namespace Microsoft.PowerShell.Commands { foreach (string key in Headers.Keys) { - // add the header value (or overwrite it if already present) - WebSession.Headers[key] = Headers[key].ToString(); + var value = Headers[key]; + + // null is not valid value for header. + // We silently ignore header if value is null. + if (!(value is null)) + { + // add the header value (or overwrite it if already present) + WebSession.Headers[key] = value.ToString(); + } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index 2e234ea594..8949d56db5 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -3496,4 +3496,19 @@ Describe "Web cmdlets tests using the cmdlet's aliases" -Tags "CI", "RequireAdmi $result = Invoke-RestMethod $uri $result.Hello | Should -Be "world" } + + It "Web cmdlets ignore headers with null value" { + $query = @{ + body = "hello" + contenttype = 'text/plain' + } + $uri = Get-WebListenerUrl -Test 'Response' -Query $query + + # Core throws if a header has null value. + # We ignore such headers so no exception is expected. + { Invoke-WebRequest -Uri $uri -Headers @{ "Location" = $null } } | Should -Not -Throw + { Invoke-WebRequest -Uri $uri -ContentType $null } | Should -Not -Throw + { Invoke-RestMethod -Uri $uri -Headers @{ "Location" = $null } } | Should -Not -Throw + { Invoke-RestMethod -Uri $uri -ContentType $null } | Should -Not -Throw + } }