Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web request timeout in .NET

I am trying to make a web service request call to a third part web site who's server is a little unreliable. Is there a way I can set a timeout on a request to this site? Something like this pseudo code:

try // for 1 minute
{
    // Make web request here
    using (WebClient client new WebClient()) //...etc.
}
catch
{
}
like image 620
Victor Avatar asked Mar 19 '10 07:03

Victor


People also ask

What is the default timeout for HTTP request in C#?

The default value is 100,000 milliseconds (100 seconds). To set an infinite timeout, set the property value to InfiniteTimeSpan. A Domain Name System (DNS) query may take up to 15 seconds to return or time out.

How do I set request timeout in .NET core?

But according to the documentation you can just add web. config to your project and specify this (and other) setting value: Setting the RequestTimeout="00:20:00" on the aspNetCore tag and deploying the site will cause it not to timeout.


2 Answers

You could use the Timeout property:

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());
}

UPDATE:

To answer the question in the comment section about XElement.Load(uri) you could do the following:

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);
}
like image 134
Darin Dimitrov Avatar answered Oct 06 '22 00:10

Darin Dimitrov


You could check for WebTimeout exception from server side then use SignalR to actively send timeout messsage back to clients:

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!");
    }
}

See more how to setup SignalR for asp.net here

like image 44
Minh Nguyen Avatar answered Oct 06 '22 00:10

Minh Nguyen