当服务器返回错误时,使用WebClient访问响应体的任何方法
本文关键字:响应 访问 方法 任何 WebClient 使用 返回 服务器 错误 | 更新日期: 2023-09-27 18:16:43
使用WebClient类时,是否有办法在响应状态为4xx时访问响应体,例如:
(webClient, evt) => // this is the event handler for the UploadStringCompleted event
{
if (evt.Error != null)
{
// can I access the response text?
}
});
错误是一个webeexception(而不是香草异常),这是我所做的(请原谅VB.NET):
''' <summary>
''' Extends a WebException to include any body text from the HTTP Response in the .Message
''' </summary>
Friend Function ExtendWebExceptionInfo(ex As Exception) As Exception
Dim wEx As WebException = TryCast(ex, WebException)
If wEx Is Nothing Then Return ex
Dim exMessage As String = Nothing
Using reader As New StreamReader(wEx.Response.GetResponseStream, System.Text.Encoding.UTF8)
exMessage = reader.ReadToEnd
End Using
If Not String.IsNullOrWhiteSpace(exMessage) Then
exMessage = String.Format("{0}{1}{1}The server says:{1}{2}", wEx.Message, vbCrLf, exMessage)
Return New WebException(exMessage, wEx, wEx.Status, wEx.Response)
End If
Return wEx
End Function