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

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...