C#: How to I extend the timeout of a WebClient call? (30 seconds is just not long enough)
My Azure function is calling web services that take longer than 30 seconds to complete, so I needed to extend the default timeout the WebClient class.
I created the following base class:
using System;
using System.Net;
namespace MyHelpers
{
public class MyWebClient : WebClient
{
public int Timeout { get; set; }
public WebDownload() : this(180000) { }
public WebDownload(int timeout)
{
this.Timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request != null)
{
request.Timeout = this.Timeout;
}
return request;
}
}
}
I set the default to 3 minutes. I can then use it like I would a usual WebClient call:
private string ExecuteAPI(string url, Dictionary<string, string> parameters)
{
try
{
using (var client = new MyWebClient())
{
foreach (var param in parameters)
{
client.Headers.Add(param.Key, param.Value);
}
return client.DownloadString(url);
}
}
catch
{
return string.Empty;
}
}
I created the following base class:
using System;
using System.Net;
namespace MyHelpers
{
public class MyWebClient : WebClient
{
public int Timeout { get; set; }
public WebDownload() : this(180000) { }
public WebDownload(int timeout)
{
this.Timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request != null)
{
request.Timeout = this.Timeout;
}
return request;
}
}
}
I set the default to 3 minutes. I can then use it like I would a usual WebClient call:
private string ExecuteAPI(string url, Dictionary<string, string> parameters)
{
try
{
using (var client = new MyWebClient())
{
foreach (var param in parameters)
{
client.Headers.Add(param.Key, param.Value);
}
return client.DownloadString(url);
}
}
catch
{
return string.Empty;
}
}
Comments
Post a Comment