c# – 当服务器返回错误时,使用WebClient访问响应主体的任何方法
发布时间:2020-12-15 17:22:18 所属栏目:百科 来源:网络整理
导读:当使用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
当使用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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |