Powershell: Invoke-RestMethod does not return response headers

Created on 30 May 2019  路  12Comments  路  Source: PowerShell/PowerShell

Background

I am responding my client request with 401 and sending back respond header with WWW-Authenticate: basic realm="apps" by following https://tools.ietf.org/html/rfc7235#section-4.1.
I can test it using postman. But I cannot use invoke-RestMethod because it does not return anything while 401.

Steps to reproduce

Invoke-RestMethod -Method Get -uri http://www.bing.comcomcomc -ResponseHeadersVariable aa
$aa      # it's empty

Expected behavior

headers should be displayed even if server response with error code.

Actual behavior

headers are empty if server responses with 401.

Environment data

6.1

Area-Cmdlets-Utility Issue-Question Resolution-Fixed

All 12 comments

Add @adityapatwardhan

It's probably just a typo in the issue but just in case -- your code sample shows you're sending the headers to variable with name aa and then retrieving the variable $dd?

thanks @vexx32 ! I fixed the typo in the repo.

I can't repro this in 7-preview1 or 6.2.0 when running the below working code

Invoke-RestMethod -Method Get -uri http://www.bing.com -ResponseHeadersVariable aa
$aa 

@kilasuit that's not a 401 response from the server though, right?

Also, /cc @markekraus

@kilasuit yes, it works for happy cases. Try the uri with error.
Invoke-RestMethod -Method Get -uri http://www.bing.comdddddd -ResponseHeadersVariable aa
In my case, I need to challenge client with 401 and expect client send me auth token header, stuff.

a 401 response is treated a failed response and we do not populate the headers on fail responses. However, this would be worked around if we implement this https://github.com/PowerShell/PowerShell/issues/5555#issuecomment-489849231

You can get the response headers from the error:

try {
  Invoke-RestMethod '...'
} catch [Microsoft.PowerShell.Commands.HttpResponseException] {
  $_.Exception.Response.Headers.WwwAuthenticate
}

Headers is a System.Net.Http.Headers.HttpResponseHeaders object.
See also Microsoft.PowerShell.Commands.HttpResponseException.

I have been struggling with this, note that httpbin.org is very handy for testing and that $_.Exception.Response.StatusCode.value__ seems to work on PowerShell 6.2.1 and 4.0. However I agree with others this should be easier especially with 2xx codes

Try this one:

$resp = try { Invoke-RestMethod -Method Get -uri http://example.com/notfound } catch { $_.Exception.Response.Headers.ToString() }

PS C:\Users\Administrator> $resp
Content-Length: 94741
Cache-Control: private
Content-Type: text/html; charset=utf-8
Date: Thu, 31 Oct 2019 13:35:17 GMT

This should also be addressed by https://github.com/PowerShell/PowerShell/pull/10466

:tada:This issue was addressed in #10466, which has now been successfully released as v7.0.0-preview.6.:tada:

Handy links:

Was this page helpful?
0 / 5 - 0 ratings