我的問題是,我的HttpClient
超時是100毫秒,所以如果我的請求通過100毫秒,我會停止請求。通常當請求通過100毫秒,我可以趕上TimeoutException
,所以我可以停止請求HttpClient超時偶爾不起作用
但偶爾請求通過500,800,2000毫秒,但我不能趕上TimeoutException
或其他例外。
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, 0, 0, 100);
client.BaseAddress = new Uri(string.Format("http://{0}/", ApiHelper._systemInfo.WebApiAddress));
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string data = JsonConvert.SerializeObject(model);
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
long time = 0;
try
{
swCheck.Restart();
HttpResponseMessage response = client.PostAsync("api/Access/CheckPlate", content).Result;
swCheck.Stop();
time = swCheck.ElapsedMilliseconds;
if (response.IsSuccessStatusCode)
{
result = new PlateCheckApiResponseModel();
string respData = response.Content.ReadAsStringAsync().Result;
result = JsonConvert.DeserializeObject<PlateCheckApiResponseModel>(respData);
}
else
{
_logger.Warn("response.IsSuccessStatusCode :" + response.StatusCode);
_logger.Info("Request Message : " + response.RequestMessage);
}
}
catch (TimeoutException ex)
{
swCheck.Stop();
time = swCheck.ElapsedMilliseconds;
_logger.Warn("Checkapi timeout ,response time: " + time);
}
catch (AggregateException)
{
swCheck.Stop();
time = swCheck.ElapsedMilliseconds;
_logger.Warn("Checkapi timeout ,response time: " + time);
}
catch (Exception ex)
{
_logger.Error(ex, "Exception");
throw ex;
}
return result;
}
這對於一個http請求來說沒有太多時間。可能是DNS解析,如備註所述:https://msdn.microsoft.com/en-us/library/system.net.http.httpclient.timeout(v=vs.110).aspx#Anchor_2 – Crowcoder
它也可以是因爲你偶爾陷入僵局。 [您應該**從不**在asp.net上下文中的異步調用中使用'.Result'。](https://blog.stephencleary.com/2012/07/dont-block-on-async-code。 HTML)。如果你不能將你的代碼轉換爲異步「一路下來」,那麼使用「HttpWebRequest」而不是「HttpClient」。 – Crowcoder
嗯,這是否會導致asp.net web api崩潰? –