在我的开发PC上,我遇到了.NET Web类的奇怪问题。 WebClient或WebRequest http" GET"到非本地主机地址通常在进程启动后不起作用。下载会持续240秒,然后超时。服务器似乎没有看到任何连接尝试。不仅其他PC没有问题,即使是同一台PC上的非.NET应用程序也没有这个问题!在一个过程中尝试一些后,问题就是该过程会自我修复,但会立即重新出现以进行新过程。 设置
request.Proxy = null
有帮助,尽管在互联网设置中没有配置代理!输出:netsh winhttp show proxy
Current WinHTTP proxy settings:
Direct access (no proxy server).
我也检查了" C:\ Windows \ Microsoft.NET \ Framework(64)\ v4.0.30319 \ Config \ web.config" 但是只有"代理"是:
<system.net>
<defaultProxy>
<proxy usesystemdefault="true" />
</defaultProxy>
</system.net>
我无法将代理设置为null,因为我还使用了第三方.net组件,我无法更改。 这里有一个小型的PowerShell脚本,可以解决这个问题。它首先使用curl来证明服务器连接正常,然后尝试WebRequest:
$url = "http://www.stackoverflow.com"
$TOOLS = "D:\Work\Main\Tools"
$responseText = $null
$time = measure-command { $responseText = (& $TOOLS\curl -y 30 -Y 1 -f $url) }
if ($lastexitcode -ne 0) { write-host "exit code is $lastexitcode" }
Write-Host " Curl took $($time.TotalSeconds) to complete"
Write-Host $($responseText[0].Substring(0,35))
$responseText = $null
$time = measure-command {
$webRequest = [System.Net.WebRequest]::Create($url)
# $webRequest.Proxy = $null
$webRequest.Timeout = 1000
$webRequest.ReadWriteTimeout = 1000
$response = $webRequest.GetResponse()
$responseStream = $response.GetResponseStream()
$textReader = New-Object System.IO.StreamReader $responseStream
$responseText = $textReader.ReadToEnd()
}
Write-Host "WebRequest took $($time.TotalSeconds) to complete"
Write-Host $($responseText[0].Substring(0,35))
输出
Curl took 0.1028601 to complete
<head><title>Document Moved</title>
Exception calling "GetResponse" with "0" argument(s): "The operation has timed out"
At C:\Users\meyerrn\Documents\curl-vs-dotnet.ps1:18 char:5
+ $response = $webRequest.GetResponse()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
WebRequest took 240.0301465 to complete
在ISE中多次启动时,它可能突然工作,然后它将一直有效,直到我重新启动ISE。 我的电脑上有什么问题?
更新:今天超时时间完全是随机的。有时240s,通常更少(例如74.13,29.76,30.38s)。 WTF?