我正在寻找一种解决方案来解析给定 Web 服务的错误响应。下面的示例通常效果很好,但如果响应大于 64kb,则异常中的内容根本不可用。
我已经看到一些解决方案建议使用 webHttpClient 并在此处增加 MaxResponseContentBufferSize,但是对于给定的 WebClient 对象,我该如何做到这一点?是否有任何选项可以为所有网络调用全局更改 BufferSize,例如 TLS12 设置?
这是我的示例代码:
# using net-webclient to use individual user-side proxy-settings:
$web = new-object Net.WebClient
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$url = "address to web-service"
try {
$response = $web.DownloadString($url)
} catch [System.Net.WebException] {
# this part needs to work even if the error-response in larger than 64kb
# unfortunately the response-object is empty in such case
$message = $_.Exception.Response
$stream = $message.GetResponseStream()
$reader = new-object System.IO.StreamReader ($stream)
$body = $reader.ReadToEnd()
write-host "#error:$body"
}