首页 > 解决方案 > 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 设置的任何提示我可以调整以解决此问题?

标签: c#asp.netiiswindows-authenticationwebclient

解决方案


看起来 Dispose() 在 using() 语句中无法正常工作:

using (WebClient client = new WebClient())
 { ... }

没有 using() 语句的解决方法:

WebClient client = new WebClient();
client.DownloadFileCompleted += OnDownloadFileCompleted;

下载完成后:

client.Dispose() 

这个对我有用。


推荐阅读