When using the System.Net.WebClient class you are actually using a class that wraps WebRequesr and WebResponse with some benefits as abstracting stream and handling logic. However, this, comes at a price and sometimes along with some errors, too.

When a web server responds with an HTTP 500 Status the WebClient throws an exception and you do not have  access to neither the ResponseHeaders or the actual payload that the server returned. This is especially nasty when the web server returns additional data to describe the error condition as this is the case with the CTERA storage portals. So better use WebRequest and WebResponse rigtht away and write your own wrapper.

You can still get the ResponseHeaders via the WebException (‘$error[0].Exception.InnerException.Response’). Check Microsoft Connect for an update on this issue.

As a side note: this behaviour actually violates the SHOULD recommendation of RFC 2616 #10.5.

=== UPDATE ===
You can actually get the server response when accessing the InnerException.Response property:

$HttpWebResponse = $_.Exception.InnerException.Response;
if($HttpWebResponse -is [System.Net.HttpWebResponse]) {
 $sr = New-Object System.IO.StreamReader($HttpWebResponse.GetResponseStream(), $true);
 $Content = $sr.ReadToEnd();
} # if

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.