有没有办法让
System.Net.WebRequest
或 System.Net.WebClient
尊重 hosts
或 lmhosts
文件?
例如:在我的主机文件中,我有:
10.0.0.1 www.bing.com
当我尝试在浏览器(IE 和 FF)中加载 Bing 时,它无法按预期加载。
Dns.GetHostAddresses("www.bing.com")[0]; // 10.0.0.1
WebRequest.Create("http://10.0.0.1").GetResponse(); // throws exception (expected)
WebRequest.Create("http://www.bing.com/").GetResponse(); // unexpectedly succeeds
同样:
WebClient wc = new WebClient();
wc.DownloadString("http://www.bing.com"); //succeeds
为什么
System.Net.Dns
尊重主机文件但System.Net.WebRequest
忽略它?我需要更改什么才能使 WebRequest 尊重主机文件?
附加信息:
编辑
根据 @Richard Beier 的建议,我尝试了
System.Net
追踪。当跟踪 ON 时,WebRequest
会失败。然而,一旦我关闭跟踪,行为就会恢复到意外的成功。我已经在调试和发布模式下在与之前相同的机器上重现了这一点。
编辑2这原来是公司代理给我们带来的问题。我们的解决方案是为我们的测试机器定制代理配置脚本,其中“bing.com”指向 DIRECT 而不是默认代理。
Dns.GetHostAddresses("www.bing.com")[0]; // 10.0.0.1
这是有效的,因为您要求操作系统获取www.bing.com
的 IP 地址
WebRequest.Create("http://www.bing.com/").GetResponse(); // unexpectedly succeeds
这是有效的,因为您要求框架从服务器名称获取路径。该框架使用与 IE 前端使用的引擎和设置相同的引擎和设置,因此,如果您的公司已通过 GPO 指定您使用公司代理服务器,则该代理服务器会解析www.bing.com
的 IP 地址,而不是你。
WebRequest.Create("http://10.0.0.1").GetResponse(); // throws exception (expected)
此方法有效/失败,因为您已要求框架从特定服务器(通过 IP)获取网页。即使您设置了代理,该代理仍然无法连接到该 IP 地址。
我希望这有帮助。
乔纳森
Console.WriteLine(Dns.GetHostAddresses("www.bing.com")[0]); // 10.0.0.1
var response = WebRequest.Create("http://www.bing.com/").GetResponse(); // * * *
Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
我在标记为“* * *”的行上遇到了异常。这是异常详细信息:
System.Net.WebException was unhandled
Message=Unable to connect to the remote server
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at ConsoleApplication2.Program.Main(String[] args) in c:\Data\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 17
InnerException: System.Net.Sockets.SocketException
Message=A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.0.0.1:80
Source=System
ErrorCode=10060
也许这是早期 .NET 版本的问题,现已在 .NET 4 / VS 2010 中修复?您使用的是哪个版本的 .NET?
我还发现了 2007 年的这个
thread,其他人也遇到了同样的问题。那里有一些很好的建议,包括以下内容:
将被绕过。
request.Proxy = new WebProxy();
以下只是代码示例:
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("www.bing.com");
request.Proxy = new WebProxy();
request.Method = "POST";
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
//some code here
}
}
catch (exception e)
{
//Some other code here
}