2010-04-11 424 views
3

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

谢谢你在前进,

杰克

+0

最大的下载或上传的最大范围内? – Aristos 2010-04-11 09:29:10

+0

@Aristos - 我在说最大的下载量。我的asp.net网页下载传递给它的url。 – 2010-04-11 11:26:56

回答

7

有没有办法做到这一点“干净”,而无需使用Flash或Silverlight文件上载控件。如果不使用这些方法,最好的做法是在web.config文件中设置maxRequestLength

实施例:

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

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

编辑DUE TO评论:

所以你可能使用了几个方法做的就是从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 
} 

另一种方法是做下载来检查文件大小之前只是做一个基本的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 
} 

希望这些解决方案或一个帮助至少让你走上正确的道路。

+0

@凯尔西 - 你的答案是无关的。请重读这个问题。 – 2010-04-12 19:39:47

+0

@Jack Juiceson - 您使用什么方法获取URL?你使用库来处理文件流? – Kelsey 2010-04-12 21:54:34

+0

感谢您的重新编辑,DownloadProgressChanged的第一个解决方案就是我要做的,这就是我一直在寻找的。关于第一个提出请求的第二个解决方案,我不会使用它,因为并非始终由服务器提供内容长度标头。 – 2010-04-13 09:15:12

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

那你决定是否bytesTotal是极限