【问题标题】:Catching timeout in C# for web service call在 C# 中捕获 Web 服务调用的超时
【发布时间】:2017-01-13 01:26:50
【问题描述】:

我正在使用 C# .Net 异步调用 Web 服务并希望添加超时。我无法弄清楚如何正确捕获超时异常。

我宁愿不使用通用异常,因为它非常广泛。首选是专门捕获超时异常并提醒用户超时。

当发生超时时,如果我打印出异常类型,我会得到 System.Net.WebException。

有没有更好的方法来捕捉超时异常?

        HttpResponseMessage response = new HttpResponseMessage();

        HttpClient client = new HttpClient();
        client.Timeout = new TimeSpan(1);

        client.BaseAddress = new Uri(dimURL);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //Response Code
        try
        {
            response = client.GetAsync(dimURL).Result;
        }
        catch (<CATCH TIMEOUT>)
        {

        }
        catch (Exception e)
        { }

【问题讨论】:

标签: c# .net-4.0


【解决方案1】:

您正在寻找WebExceptionHere 是 MSDN 页面。

【讨论】:

    猜你喜欢
    • 2011-06-18
    • 1970-01-01
    • 2010-09-23
    • 2015-02-15
    • 2014-03-31
    • 1970-01-01
    • 2012-02-26
    • 2013-08-24
    • 1970-01-01
    相关资源
    最近更新 更多