微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 当服务器返回错误时,使用WebClient访问响应主体的任何方法?

当使用WebClient类时响应状态为4xx时,是否有办法访问响应正文,例如:

(webClient,evt) => // this is the event handler for the UploadStringCompleted event
    {
        if (evt.Error != null)
        {
            // can I access the response text?
        }
    });

解决方法

由于evt.Error是一个WebException(而不是一个vanilla异常),这就是我所做的(请原谅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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐