限制WebClient DownloadFile最大文件大小

Jac*_*son 4 .net asp.net webclient http

在我的asp .net项目中,我的主页接收URL作为我需要在内部下载然后处理它的参数.我知道我可以使用WebClient的DownloadFile方法但是我想避免恶意用户给一个巨大的文件提供一个url,这会从我的服务器获得不必要的流量.为了避免这种情况,我正在寻找一种解决方案来设置DownloadFile将下载的最大文件大小.

先感谢您,

插口

Kel*_*sey 7

如果不使用flash或silverlight文件上传控件,就无法"干净利落".如果不使用这些方法,最好的办法就是maxRequestLength在web.config文件中设置.

例:

<system.web>
    <httpRuntime maxRequestLength="1024"/>
Run Code Online (Sandbox Code Playgroud)

上面的示例将文件大小限制为1MB.如果用户尝试发送任何更大的内容,他们将收到一条错误消息,指出已超出最大请求长度.这不是一个漂亮的消息,但如果你想,你可以覆盖IIS中的错误页面,使其可能与您的网站匹配.

根据评论编辑:

所以你可能使用几种方法来从URL获取文件的请求,所以我将发布2个可能的解决方案.首先是使用.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
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是在执行下载之前执行基本Web请求以检查文件大小:

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
}
Run Code Online (Sandbox Code Playgroud)

希望其中一个解决方案有助于或至少让您走上正确的道路.