HttpClient MaxResponseContentBufferSize 未按预期工作

问题描述 投票:0回答:1

这是我的简单代码:

    var c = new System.Net.Http.HttpClient();
    c.MaxResponseContentBufferSize = 100;
    await c.GetAsync("https://stackoverflow.com/");

MaxResponseContentBufferSize
小于真实响应大小时,
GetAsync
方法根本不会结束。

我需要如果响应超过给定的

MaxResponseContentBufferSize
,它会停止请求。那么问题出在哪里呢?

c# httpclient
1个回答
1
投票

那是因为执行 GetAsync 时的这段代码

private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error)
{
    error = null;
    long? contentLength = Headers.ContentLength;
    if (contentLength.HasValue)
    {
        if (contentLength > maxBufferSize)
        {
             error = new HttpRequestException(SR.Format(CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize));
            return null;
        }
        return new LimitMemoryStream((int)maxBufferSize, (int)contentLength.Value);
    }
    return new LimitMemoryStream((int)maxBufferSize, 0);
}

结果还好

© www.soinside.com 2019 - 2024. All rights reserved.