这是我的简单代码:
var c = new System.Net.Http.HttpClient();
c.MaxResponseContentBufferSize = 100;
await c.GetAsync("https://stackoverflow.com/");
当
MaxResponseContentBufferSize
小于真实响应大小时,GetAsync
方法根本不会结束。
我需要如果响应超过给定的
MaxResponseContentBufferSize
,它会停止请求。那么问题出在哪里呢?
那是因为执行 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);
}