【问题标题】:Is it safe to discard HttpResponseMessage without reading the content?在不阅读内容的情况下丢弃 HttpResponseMessage 是否安全?
【发布时间】:2018-07-23 18:53:49
【问题描述】:

我正在使用HttpClient 来获取HttpResponseMessage 对象。根据标头,我实际上并不关心响应正文,因此我不想阅读正文内容,只需丢弃它。

我在网上看到了一些示例,这些示例即使在内容字节被立即丢弃的情况下也会读取响应正文,我试图了解这是否有必要。例如,我发现了这个 GitHub gist,第 124 行:

if (DownloadContentOnRedirect && response.Content != null)
{
    await response.Content.ReadAsByteArrayAsync();
}

这是我正在做的一个例子:

using (var request = new HttpRequestMessage(HttpMethod.Get, uri))
{
    var response = await (httpClient.SendAsync(request, CancellationToken.None));

    // Some code here related to the work being done but not 
    // touching the response.

    if (!CheckSomeHeaders(response))
    {
        // Response may have large body. Do not read, discard.
        response.Dispose(); // Is this correct / enough?
    }
    else
    {
        // Do some other stuff. Response will be returned to
        // caller and caller is responsible for handling it.
    }
}

如果我已经知道我不感兴趣,我想避免阅读响应正文(正文可能很长)。 注意,response 故意不在using 块内;在某些情况下,响应可能会返回给调用者。

以上要点是必要的步骤,还是只调用 Dispose() 以避免资源泄漏是否安全。我想不出有必要阅读内容的情况,但也许我忽略了一些东西。

【问题讨论】:

    标签: c# .net dotnet-httpclient


    【解决方案1】:

    以上要点是否是必要的步骤

    没有。

    只调用Dispose() 以避免资源泄漏是否安全。

    是的。

    但大多数情况下没有必要。如果将其重构为包装在 using 中,它将在超出范围时被处置

    【讨论】:

    • 谢谢 - 这是我的怀疑。我的response 不是故意在using 块内 - 有时响应会返回给调用者,调用者决定如何处理它。有时我自己的代码会提前丢弃它并继续。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    相关资源
    最近更新 更多