[英]synchronous call httpclienthandler does not wait
I do a call to the following, but I notice that if the webapi i'm calling takes longer than 41 seconds it will just return leading to a null value. 我对以下内容进行了调用,但我注意到,如果我正在调用的webapi花费的时间超过41秒,它将返回导致返回null值。
I tried setting the client.timeout setting but that did not seem to make a difference. 我尝试设置client.timeout设置,但这似乎没有什么不同。 What am I doing wrong? 我究竟做错了什么?
HttpClientHandler handler = new HttpClientHandler()
{
Credentials = credentials
};
using (var client = new System.Net.Http.HttpClient(handler))
{
client.Timeout.Add(new TimeSpan(1, 0, 0));
client.BaseAddress = new Uri(site.ToString());
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
try
{
string target = site.ToString() + apiPath + query;
var response = client.GetAsync(target).Result;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
var result =
response.Content.ReadAsStringAsync().Result;
if (!String.IsNullOrEmpty(result))
{
return result;
}
else
{
return null;
}
}
else
{
return null;
}
}
catch (Exception ex)
{
return null;
}
}
This line: 这行:
client.Timeout.Add(new TimeSpan(1, 0, 0));
does nothing, because TimeSpan is immutable. 什么都不做,因为TimeSpan是不可变的。 It just returns a value, which you then don't use. 它只是返回一个值,您将不再使用它。 I presume you instead want: 我想你反而想要:
client.Timeout = new TimeSpan(1, 0, 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.