.NET中的Web请求超时

时间:2010-03-19 07:18:36

标签: c# .net asp.net-mvc web-services

我正在尝试向第三方网站发送Web服务请求,该网站的服务器有点不可靠。有没有办法可以在对此站点的请求上设置超时?像这样的伪代码:

try // for 1 minute
{
    // Make web request here
    using (WebClient client new WebClient()) //...etc.
}
catch
{
}

5 个答案:

答案 0 :(得分:23)

您可以使用Timeout属性:

var request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
request.Timeout = 1000; //Timeout after 1000 ms
using (var stream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(stream))
{
    Console.WriteLine(reader.ReadToEnd());
}

更新:

要回答有关XElement.Load(uri)的评论部分中的问题,您可以执行以下操作:

var request = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com/feeds");
request.Timeout = 1000; //Timeout after 1000 ms
using (var stream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(stream))
{
    var xel = XElement.Load(reader);
}

答案 1 :(得分:4)

WebClient自然不支持自定义超时。但是您可以使用自定义超时轻松构建派生类:

public class TimeoutWebClient : WebClient
{
    private int _timeOut = 10000;
    public int TimeOut
    {
        get
        {
            return _timeOut;
        }
        set
        {
            _timeOut = value;
        }
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest webRequest = base.GetWebRequest(address);
        webRequest.Timeout = _timeOut;
        return webRequest;
    }
}

来源:http://aspadvice.com/blogs/maniknet/archive/2008/06/16/Ganz-kurz_3A00_-WebClient-mit-eigenem-Verbindungs-Timeout-_2800_WebClient-with-a-custom-connection-timeout_2900_.aspx

答案 2 :(得分:2)

也许你应该选择

System.Net.WebRequest.Timeout
属性

答案 3 :(得分:1)

您可以从服务器端检查WebTimeout异常,然后使用SignalR主动将超时消息发送回客户端:

var request = (HttpWebRequest)WebRequest.Create("http://www.your_third_parties_page.com");
request.Timeout = 1000; //Timeout after 1000 ms

try
{
    using (var stream = request.GetResponse().GetResponseStream())
    using (var reader = new StreamReader(stream))
    {
         Console.WriteLine(reader.ReadToEnd());
    }
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.Timeout)
    {
         //If timeout then send SignalR message to inform the clients...
         var context = GlobalHost.ConnectionManager.GetHubContext<YourHub>();
         context.Clients.All.addNewMessageToPage("This behavious have been processing too long!");
    }
}

查看更多how to setup SignalR for asp.net here

答案 4 :(得分:0)

.Net框架中涉及任何类型网络的许多类都包含Timeout属性。例如,WebRequest类(System.Net)上有这样的属性