c# - C# WebClient DownloadFile 只工作一次
问题描述
我构建了一个函数,从我的网站(.NET webforms,旧应用程序)下载一系列报告,将它们保存为临时文件夹中的 .html 文件,压缩它们并将存档返回给用户。该应用程序使用 Windows 身份验证,我设法通过启用在请求中传递当前用户凭据
Credentials = CredentialCache.DefaultCredentials
一切都在我的开发环境中无缝运行(在 IIS Express 和 IIS 上),但在生产服务器(Windows server 2008 R2,IIS 7.5)上,只有当我将周期限制为一次迭代时它才有效。看起来 WebClient 底层连接保持打开状态,服务器拒绝在下一个周期打开另一个连接。我得到的错误信息是
请求被中止:无法创建 SSL/TLS 安全通道。
并且,启用 WCF 跟踪,我可以将问题缩小到“401 未授权”错误。
这是我的功能的重要部分:
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()
这个对我有用。
推荐阅读
- typescript - 使用nodejs ECMAScript模块时如何配置打字稿
- pytest - 为字符串匹配实现自定义断言
- python-3.x - PyQt - 结合 QSlider 和 QTextEdit
- java - 如何设置 JButton 的背景?
- go - Golang Kafka Reader 无法从主题中读取消息
- entity-framework-core - 锁定表实体框架核心的最佳方法
- angular - 在角度 2 中比较 2 次
- sql-server - 绕过 SQL 错误 264 - 在 SET 子句中多次指定列名
- python - Scikit-Learn - one-hot 编码熊猫数据帧的某些列
- sql - Oracle如何根据月份数对列求和