Limit WebClient DownloadFile Maximum File Size

In my asp.net project, my main page receives the URL as a parameter, which I need to load inside and then process it. I know that I can use the WebClient DownloadFile method, however I want the attacker to not give out the URL to a huge file, which will lead to unnecessary traffic from my server. To avoid this, I'm looking for a solution to set the maximum file size that DownloadFile will upload.

Thanks in advance,

Jack

+3
source share
2 answers

"" flash silverlight. , , , - maxRequestLength web.config.

:

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

1 . - , , , . , , ​​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
}

, - , :

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
}

, , , .

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

, bytesTotal

+1

Source: https://habr.com/ru/post/1740636/


All Articles