我打电话给以下人员,但是我注意到如果我正在调用的webapi超过41秒,它将返回导致空值。
我尝试设置client.timeout设置,但这似乎没有什么区别。我究竟做错了什么?
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;
}
}
答案 0 :(得分:1)
这一行:
client.Timeout.Add(new TimeSpan(1, 0, 0));
什么都不做,因为TimeSpan是不可变的。它只返回一个您不能使用的值。我认为你想要:
client.Timeout = new TimeSpan(1, 0, 0);