HttpWebRequest times out with multiple network adaptors enabled
On my Win7 PC I have a couple of virtual network adaptors that are used for VMWare server. My HttpWebRequest times out when I have these adaptors enabled. Should I really have to tell it which adaptor to bind to?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.AbsoluteUri + "etc.txt");
request.Timeout = 2000;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
开发者_如何学C {
return reader.ReadToEnd();
}
}
UPDATE
I'm guessing this is a common issue. Does anybody have a standard way to handle this? I cant really prompt the user for the interface as they are non tech. Rohit's answer is good start at showing how to set the ServicePoint.
Tim, If you are seeing timeout it is because your new adapters have route for the URL and they are not reaching the destination.
public delegate IPEndPoint BindIPEndPoint(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount);
You can use it as
private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint,IPEndPoint remoteEndPoint, int retryCount)
{
if(retryCount < 3)
return new IPEndPoint(IPAddress.Parse("192.168.10.60"), 0);
else
return new IPEndPoint(IPAddress.Any, 0);
}
and...
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
See http://www.netbrick.net/blog/PermaLink,guid,b9c255d9-74b4-45ab-8fd0-c9a04784655a.aspx for more details.
Following on from Rohits answer. Would this work well at trying all the adaptors?
private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
List<IPEndPoint> endPoints = new List<IPEndPoint>();
foreach (NetworkInterface netinface in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (IPAddressInformation unicast in netinface.GetIPProperties().UnicastAddresses)
{
if(unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
endPoints.Add(new IPEndPoint(unicast.Address, 80));
}
}
if (retryCount > endPoints.Count - 1)
return new IPEndPoint(IPAddress.Any, 80);
else
return endPoints[retryCount];
}
精彩评论