c# - 流 ReadAsStreamAsync (ReadTimeout = Timeout.Infinite) + json = 此流不支持超时。
问题描述
我需要发送一个 post HTTP 请求,并将 json 结果转换为 IEnumerable。
到目前为止我所拥有的:
public IEnumerable<T> GetDataStream<T>(string baseURL, string query, string HTTPMethod) where T : IEntity, new()
{
var stopWatch = new Stopwatch();
log.Info($"HttpMethod : [{HTTPMethod}] - Query: {query}");
stopWatch.Start();
var handler = new HttpClientHandler { UseDefaultCredentials = true };
var client = new HttpClient(handler) { Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite) };
var requestMethod = HTTPMethod == "GET" ? HttpMethod.Get : HttpMethod.Post;
var request = new HttpRequestMessage(requestMethod, requestMethod == HttpMethod.Get ? $"{baseURL}?query={query}" : baseURL);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
var tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(TimeSpan.FromMilliseconds(Timeout.Infinite));
if (requestMethod == HttpMethod.Get)
{
response = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, tokenSource.Token).Result;
}
else
{
var content = new StringContent(query, Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response = client.PostAsync(baseURL, content, tokenSource.Token).Result;
}
response.EnsureSuccessStatusCode();
using (var stream = response.Content.ReadAsStreamAsync().Result)
{
stream.ReadTimeout = Timeout.Infinite;
using (var sr = new StreamReader(stream, Encoding.UTF8))
using (var jr = new JsonTextReader(sr))
{
var serializer = new JsonSerializer();
while (jr.Read())
{
if (jr.TokenType != JsonToken.StartArray && jr.TokenType != JsonToken.EndArray)
{
yield return serializer.Deserialize<T>(jr);
}
}
}
}
stopWatch.Stop();
log.Debug($"Total time : {stopWatch.Elapsed:m\\:ss\\.ff}");
}
但我面临以下错误:
System.InvalidOperationException: 'Timeouts are not supported on this stream.'
这是来自这一行:
stream.ReadTimeout = Timeout.Infinite;
我认为这是因为我还将这段代码与 JSON Deserialize 调用相结合。我不知道如何为此流使用无限超时。
解决方案
推荐阅读
- visual-studio-2017 - SQL71501:列 [dbo].[columnname] 对列加密密钥 [keyname] 的引用未解析
- php - 在 Woocommerce 中作为密件抄送发送给管理员的新帐户电子邮件通知
- node.js - 处理嵌套请求中的节点请求响应
- android - 练习二活动的问题(codelabs 指南)
- rust - 当 Release 仅发生在互斥锁的锁定区域时,我是否需要 Acquire/Release?
- postman - 如何在邮递员的数据文件中提供多个主机名
- godot - 双击跳转到文本末尾
- pandas - 使用 groupby 条件迭代 Pandas DataFrame 中的列
- ruby-on-rails - 通过 Rails 电子邮件元数据发送网格 SMTP
- reactjs - 我无法在 fullcalendar 上使用资源