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
{
}
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.
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.
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With