如何从HttpRequestException获取JSON错误消息

我有一种情况,我必须在一个catch语句中提取一个Response( HttpResponseMessage ),但我认为无法完成(在catch中使用await )。 此外,如果我在catch之后执行此操作,则HttpResponseMessage消息将获得“Disposed”。 码:

  private async void MakeHttpClientPostRequest() { HttpResponseMessage response = null; try { HttpClient httpClient = new HttpClient(); httpClient.Timeout = TimeSpan.FromSeconds(15); HttpContent httpContent = null; if (postJSON != null) { httpContent = new StringContent(postJSON); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); } response = await httpClient.PostAsync(url, httpContent); if (response != null) { response.EnsureSuccessStatusCode(); netResults = await response.Content.ReadAsStringAsync(); } if (this.convertedType != null) { MemoryStream assetReader = GetMemoryStreamFromString(netResults); assetReader.Position = 0; object value = fromJSON(assetReader, this.convertedType); networkReqSuccessWithObjectCallback(this, value); } else { //Return netResult as string. networkReqSuccessWithStringCallback(this, netResults); } } catch (TaskCanceledException) { ErrorException ee = null; ee = new ErrorException("RequestTimeOut"); NotifyNetworkDelegates(ee); } catch (HttpRequestException ex) { //HERE I have to extract the JSON string send by the server } catch (Exception) { } } 

这可以做什么?


使用HttpWebRequest 更新以前的方法:

 public void MakePostWebRequest() { //WebCalls using HttpWebrequest. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.CookieContainer = new CookieContainer(); request.ContentType = "application/json"; request.Method = "POST"; requestState = RequestState.ERequestStarted; asyncResult = request.BeginGetRequestStream(new AsyncCallback(GetRequestStream), request); } private void GetRequestStream(IAsyncResult asyncResult) { HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; { try { Stream requestStream = request.EndGetRequestStream(asyncResult); if (request != null) { using (requestStream) { StreamWriter writer = new StreamWriter(requestStream); writer.Write(postJSON); writer.Flush(); } } } catch (WebException we) { } } } private void GetResponseStream(IAsyncResult asyncResult) { requestState = RequestState.EResponseStream; HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest; HttpWebResponse response; try { response = (HttpWebResponse)request.EndGetResponse(asyncResult); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { netResults = reader.ReadToEnd(); } requestState = RequestState.ERequestCompleted; } catch (WebException we) { // failure ErrorException ee = null; response = we.Response as HttpWebResponse; if (response != null) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { //HERE I'm getting the json error message netResults = reader.ReadToEnd(); } } } catch (Exception e) { networkReqFailedCallback(this, e); } } 

我强烈怀疑问题是您调用EnsureSuccessStatusCode 实际引发了exception,其文档包含:

如果Content不为null,则此方法还将调用Dispose以释放托管和非托管资源。

基本上,如果您需要失败的内容,听起来您不应该使用该方法来确定成功或失败。

只需自己检查状态代码,并根据该代码适当地使用内容。 请注意,如果请求完全失败,在catch块中response很容易为null。

这样做的正确方法是在try块本身内

 try{ ... response = await httpClient.PostAsync(url, httpContent); netResults = await response.Content.ReadAsStringAsync(); //do something with the result } catch(HttpRequestException ex) { // catch any exception here } 

catch块用于处理exception情况,然后在需要时重新抛出它们,并且应该避免执行任何其他操作。

只有在远程服务器实际响应时,才应提供响应。 如果Response为null (因为我知道这是你的情况),这意味着由于某些原因,请求未被传递或者没有收到响应(没有得到响应 – 使用代码200(OK)或任何其他代码(ERROR))。 请检查错误代码( we.Status )。 确保它等于WebExceptionStatus.ProtocolError (即服务器响应错误); 否则,发生了一些其他错误,并且响应不应该可用。