c# - 当服务器返回错误时,有什么方法可以使用 WebClient 访问响应主体?

标签 c# .net windows-phone-7.1 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 Exception),这就是我所做的(请原谅 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

关于c# - 当服务器返回错误时,有什么方法可以使用 WebClient 访问响应主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8381576/

相关文章:

c#在SplitContainer中使用TreeView控件改变内容

c# - .NET自动测试工具

.net - 使用 web.config 中的重写规则无法对子页面进行规范重写

c# - 是否有 .NET Framework 方法来解析电子邮件 (MIME)?

.net - 为什么有时用十六进制字符填充进程镜像名称?

c# - WP7 中的未处理异常

windows-phone-7 - 在 WP8 模拟器上运行 WP7.1 应用程序

windows-phone-7 - 获取 Windows Phone 7 唯一标识符的正确方法是什么?

c# - 如何使用 LINQ 将共享 1 个属性的两个列表合并为第三个列表?

c# - 使用 Windows 10 的 crystalreportviewer