【发布时间】:2016-03-21 01:10:25
【问题描述】:
我调用了以下内容,但我注意到如果我调用的 webapi 花费的时间超过 41 秒,它只会返回导致 null 值。
我尝试设置 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;
}
}
【问题讨论】:
-
也许是 API 没有返回任何东西?你用嗅探器检查过吗?
-
这是有效的,(a)当我通过 powershell 调用它时,我确实在大约 1.5 分钟后得到了结果,(b)通过 nlogs 我看到大约 30 秒后 web api 中发生了一些事情(所以在它已经超时之后)(目标 web api 只是继续)。
-
“所以在它已经超时之后” 你设置的超时时间是 1 小时 1 分 40 秒 (
client.Timeout.Add(new TimeSpan(1, 0, 0));),怎么可能已经超时了1 分 30 秒? -
BTW
if (response.IsSuccessStatusCode)没用,EnsureSuccessStatusCode抛出异常是状态码不是成功的。 -
41 秒后进入异常,所以在这个: var result = response.Content.ReadAsStringAsync().Result;出现异常消息时出现多个错误。直接调用 web api 或使用不同的参数导致少于 41 秒的事情可以正常工作。
标签: c# .net timeout dotnet-httpclient