【问题标题】:Losing error message with Http Status code 503 in System.net.Http library在 System.net.Http 库中丢失带有 Http 状态代码 503 的错误消息
【发布时间】:2020-04-21 05:42:36
【问题描述】:

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

其中一个在满足特定条件时返回 HTTP 状态代码 503 和一些响应消息(“数据不可用”),如下图所示

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

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,这是理想的情况,但问题是,当我丢失从第一个服务发送的消息(“数据不可用”)时尝试在调试窗口中打印响应,结果如下:

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 中读取响应内容?

【问题讨论】:

    标签: c# .net system.net.httpwebrequest


    【解决方案1】:

    找到了解决办法,可以阅读System.net.WebException的回复

    catch(WebException ex)
    {
          HttpWebResponse errorResponse = webException.Response as HttpWebResponse;
    
          var statusDescription = errorResponse.StatusDescription;
          if(statusDescription.Contains("XXXXX"))
          {
             // Added the condition here
          }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-23
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多