[英]C# WebClient DownloadFile works only once
我構建了一個 function,它從我的網站(.NET webforms,舊應用程序)下載一系列報告,將它們另存為 .html 文件在臨時文件夾中,壓縮它們並將存檔返回給用戶。 該應用程序使用 windows 身份驗證,我設法通過啟用在請求中傳遞當前用戶憑據
Credentials = CredentialCache.DefaultCredentials
一切都在我的開發環境中無縫運行(在 IIS 上的 IIS Express 中),但在生產服務器(Windows 服務器 2008 R2,IIS 7.5)上,它只有在我將周期限制為僅一次迭代時才有效。 看起來 WebClient 底層連接保持打開狀態,服務器拒絕在下一個周期打開另一個連接。 我得到的錯誤信息是
請求被中止:無法創建 SSL/TLS 安全通道。
並且,啟用 WCF 跟蹤,我可以將問題縮小到“401 未授權”錯誤。
這是我的 function 的重要部分:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
SecurityProtocolType.Tls12 |
SecurityProtocolType.Tls11;
foreach (var project in list.Take(1)) //fails if I try list.Take(2) or more
{
using (WebClient client = new WebClient
{
Credentials = CredentialCache.DefaultCredentials
})
{
UriBuilder address = new UriBuilder
{
Scheme = Request.Url.Scheme,
Host = Request.Url.Host,
Port = Request.Url.Port,
Path = "/ERP_ProjectPrint.aspx",
Query = string.Format("bpId={0}&bpVid={1}", project.Id, project.VersionId)
};
string fileName = project.VersionProtocol + ".html";
client.DownloadFile(address.Uri.ToString(), tempFilePath + fileName);
}
}
關於 IIS 設置的任何提示我可以調整以解決此問題?
看起來 Dispose() 在 using() 語句中無法正常工作:
using (WebClient client = new WebClient())
{ ... }
沒有 using() 語句的解決方法:
WebClient client = new WebClient();
client.DownloadFileCompleted += OnDownloadFileCompleted;
下載完成后:
client.Dispose()
這個對我有用。
嘗試將您循環到您的請求中,如下所示。 這有什么區別嗎?
也不要認為你需要使用 list.Take
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
SecurityProtocolType.Tls12 |
SecurityProtocolType.Tls11;
System.Net.ServicePointManager.DefaultConnectionLimit = 10
using (WebClient client = new WebClient
{
Credentials = CredentialCache.DefaultCredentials
})
{
foreach (var project in list)
{
UriBuilder address = new UriBuilder
{
Scheme = Request.Url.Scheme,
Host = Request.Url.Host,
Port = Request.Url.Port,
Path = "/ERP_ProjectPrint.aspx",
Query = string.Format("bpId={0}&bpVid={1}", project.Id, project.VersionId)
};
string fileName = project.VersionProtocol + ".html";
client.DownloadFileTaskAsync(address.Uri.ToString(), tempFilePath + fileName).Wait();
}
}
}
該問題已通過在服務器上啟用 TLS 1.2 得到解決:默認情況下未啟用。 請參閱https://tecadmin.net/enable-tls-on-windows-server-and-iis/ 。
請注意,啟用它可能會破壞與您的服務器的 RDP 連接功能。
感謝 Jokies Ding 為我指明了正確的方向(見上面的評論)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.