HttpClient Timeout偶尔不起作用

时间:2017-05-06 12:20:43

标签: c# asp.net-web-api

我的问题是我的HttpClient超时是100毫秒,所以如果我的请求超过100毫秒,我将停止请求。通常当请求超过100毫秒时,我可以捕获TimeoutException,因此我可以停止请求

但偶尔请求传递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;
}

1 个答案:

答案 0 :(得分:0)

MSDN documentation说:

  

域名系统(DNS)查询最多可能需要15秒才能返回或超时。如果您的请求包含需要解析的主机名,并且您将Timeout设置为小于15秒的值,则可能需要15秒或更长时间才会抛出WebException以指示请求超时。

如果您的ApiHelper._systemInfo.WebApiAddress包含域名,则可能是原因。