Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebClient.UploadFile failed with "The request was aborted: The request was canceled."

I am trying to upload a file to a HTTP URL with WebClient.UploadFile. For small file such as 1M, 2M, the uploading is successful. But for a big file such as 12M, I got this exception:

The request was aborted: The request was canceled.

Has anyone met this problem before and could you share the solution?

Some info:

  • The server is using ASP.NET 3.5.
  • The HTTP method I used in uploading is "PUT".
like image 262
smwikipedia Avatar asked Aug 15 '11 03:08

smwikipedia


1 Answers

Here is the solution referred to in smwikipedia's answer. I've added the ability to disable write stream buffering, which can help with out of memory exceptions.

public class ExtendedWebClient : WebClient
{
    public int Timeout { get; set; }
    public new bool AllowWriteStreamBuffering { get; set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request != null)
        {
            request.Timeout = Timeout;
            var httpRequest = request as HttpWebRequest;
            if (httpRequest != null)
            {
                httpRequest.AllowWriteStreamBuffering = AllowWriteStreamBuffering;
            }
        }
        return request;
    }

    public ExtendedWebClient()
    {
        Timeout = 100000; // the standard HTTP Request Timeout default
    }
}

Usage:

var webClient = new ExtendedWebClient();
webClient.Timeout = Timeout.Infinite;
webClient.AllowWriteStreamBuffering = false;
webClient.UploadFile(url, filePath);
like image 194
ctsears Avatar answered Nov 15 '22 11:11

ctsears