在 System.net.Http 库中丢失带有 Http 状态代码 503 的错误消息

Losing error message with Http Status code 503 in System.net.Http library

我们有 2 个后端服务相互通信,它们都使用 .net 框架和 System.net.Http library

其中之一 returns HTTP 状态代码 503 以及满足特定条件时的一些响应消息 ("data is not available"),如下面的屏幕截图所示

控制器代码实现如下所示:

HttpResponseMessage response = new HttpResponseMessage { StatusCode = HttpStatusCode.ServiceUnavailable, ReasonPhrase = "XXXXXX data is currently not available XXXXXXXXX" };
response.Content = new StringContent("XXXXXX is currently not available XXXXXXXXXX");
return response;

调用此 API 的其他服务正在使用响应并获取此 WebException,这是理想的情况,但问题是,我们丢失了从第一项服务,当我尝试在调试 window 中打印响应时,它显示了以下结果:

HttpWebResponse aresponse = request.GetResponse() as HttpWebResponse;
'HttpWebResponse aresponse = request.GetResponse() as HttpWebResponse' threw an exception of type 'System.Net.WebException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2146233079
    HelpLink: null
    InnerException: null
    Message: "The remote server returned an error: (503) Server Unavailable."
    Response: {System.Net.HttpWebResponse}
    Source: "System"
    StackTrace: null
    Status: ProtocolError
    TargetSite: null

如输出消息所示,不是我从第一个服务发送的消息。这是 HTTP 状态代码 503 的默认消息。

有没有办法让我从WebException中读取响应内容?

已找到解决方案,您可以阅读 System.net.WebException

的回复
catch(WebException ex)
{
      HttpWebResponse errorResponse = webException.Response as HttpWebResponse;

      var statusDescription = errorResponse.StatusDescription;
      if(statusDescription.Contains("XXXXX"))
      {
         // Added the condition here
      }
}