【问题标题】:Is there any way how to get HttpResponseMessage.Content body when response is HttpStatusCode.NoContent?当响应为 HttpStatusCode.NoContent 时,有什么方法可以获取 HttpResponseMessage.Content 正文?
【发布时间】:2019-11-20 14:37:26
【问题描述】:

我正在使用 C# 和 .NET Core 3.0

目前,当我向服务器发送 GET 请求并返回状态为 204 的响应时,似乎 System.Net.Http.HttpClient 从中剥离了正文,我无法读取其内容。

var request = new HttpRequestMessage(HttpMethod.Get,$"/gettask.ashx?testerror=20");
var response = await _httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();

我知道服务器在状态为 204 时也返回正文。我用 Curl 对其进行了测试,它返回此正文为 204 { "nextRequestInSec" : 10 }

来自 curl 的详细回复:

curl http://address.dom/testerror=204 -v
*   Trying xxx.xxx.xxx.xxx...
* TCP_NODELAY set
* Connected to address.dom (xxx.xxx.xxx.xxx) port 80 (#0)
> GET testerror=204 HTTP/1.1
> Host: address.dom
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 204 No Content
< Cache-Control: private
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=utf-8
< Server: Microsoft-IIS/8.5
< X-AspNet-Version: 4.0.30319
< X-Powered-By: ASP.NET
< Date: Wed, 20 Nov 2019 13:45:00 GMT
<
{ "nextRequestInSec" : 10 }* Connection #0 to host address.dom left intact

对于其他响应(200、401、403、404、420、500),它可以正常工作,我也可以阅读正文。

有什么办法可以到达这个身体吗?

【问题讨论】:

  • 看起来好像你无法得到它:github.com/dotnet/corefx/blob/…
  • 确定 curl 显示正文吗?我很怀疑,所以我自己做了一个测试,它切断了响应
  • @richzilla 我已经编辑了这个问题 - 看看那里的 curl 响应。

标签: c# asp.net-core dotnet-httpclient


【解决方案1】:

正如@peinarydevelopment 在他们的评论中提到的,httpclient 实例不会为不支持的状态代码返回正文。解决您的问题的最佳方法是修复服务器(或询问负责它的人)。

如果你真的必须处理损坏的 HTTP 服务器,你可以降到 TCP 级别并直接从套接字检索数据包,这似乎是一个很长的问题解决方法。

【讨论】:

    【解决方案2】:

    204 表示没有内容,所以在阅读内容之前检查状态码。 如果您想返回数据,请更改您的状态码,因为 204 不应该。

    var request = new HttpRequestMessage(HttpMethod.Get,$"/gettask.ashx?testerror=20");
    var response = await _httpClient.SendAsync(request);
    var responseContent = (response.IsSuccessStatusCode && response.StatusCode !=204)? await 
                          response.Content.ReadAsStringAsync():null;
    

    【讨论】:

    • 一般来说 - 204 只是一个状态,身体就是身体。我收到哪种状态并不重要......
    • 状态是为某事而设的,例如解析响应的方式
    • 你是对的——我看错了。
    【解决方案3】:

    好吧,看来我有点失明了。事实是,根据HttpClient

    ,在 .NET Core 这是不可能的

    此外,如果您将其视为 HTTP 通信,它应该遵循HTTP specification,它表示:

    204 响应不得包含消息正文,因此始终以标头字段后的第一个空行终止。

    【讨论】:

      猜你喜欢
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多