限制WebClient DownloadFile的最大文件大小

4
在我的asp .net项目中,我的主页面接收URL作为参数,我需要内部下载并处理它。我知道我可以使用WebClient的DownloadFile方法,但我想避免恶意用户提供一个巨大文件的url,这将导致我的服务器产生不必要的流量。为了避免这种情况,我正在寻找一种解决方案来设置DownloadFile将下载的最大文件大小。
谢谢您的帮助,
杰克

最大下载还是最大上传? - Aristos
@Aristos - 我在谈论最大下载量。我的asp .net页面会下载传递给它的url。 - Jack Juiceson
2个回答

7

如果不使用Flash或Silverlight文件上传控件,就没有办法“干净地”实现这一点。在不使用这些方法的情况下,您可以在web.config文件中设置maxRequestLength

示例:

<system.web>
    <httpRuntime maxRequestLength="1024"/>

上面的示例将文件大小限制为1MB。如果用户尝试发送任何大于此大小的内容,他们将收到一个错误消息,指出已超过最大请求长度。虽然这不是一个美观的消息,但如果您想要,可以在IIS中覆盖错误页面,使其与您的站点匹配。
由于评论,我将提供两种可能的解决方案,因为您可能正在使用几种方法来请求从URL获取文件。第一种方法是使用.NET的WebClient:
// This will get the file
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(DownloadCompleted);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
webClient.DownloadFileAsync(new Uri("http://www.somewhere.com/test.txt"), @"c:\test.txt");

private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    WebClient webClient = (WebClient)(sender);
    // Cancel download if we are going to download more than we allow
    if (e.TotalBytesToReceive > iMaxNumberOfBytesToAllow)
    {
        webClient.CancelAsync();
    }
}

private void DownloadCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
    // Do something
}

另一种方法是在下载之前进行基本的网络请求以检查文件大小:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://www.somewhere.com/test.txt"));
webRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Int64 fileSize = webResponse.ContentLength;
if (fileSize < iMaxNumberOfBytesToAllow)
{
    // Download the file
}

希望这些解决方案能够帮到你,或者至少让你走上正确的道路。

@Kelsey - 你的回答与问题无关。请重新阅读问题。 - Jack Juiceson
@Jack Juiceson - 你用什么方法获取URL?你使用库来处理文件流吗? - Kelsey
感谢重新编辑,我将采用使用DownloadProgressChanged的第一种解决方案,这正是我所需要的。关于第二种解决方案建议先进行请求的做法,我不会使用它,因为服务器并不总是提供content-length头信息。 - Jack Juiceson
你自己测试过吗?使用 DownloadProgressChangedEventHandler 的解决方案不起作用。 - Toolkit

2
var webClient = new WebClient();
client.OpenRead(url);
Int64 bytesTotal = Convert.ToInt64(client.ResponseHeaders["Content-Length"]);

然后您可以决定 bytesTotal 是否在限制范围内。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接