【问题标题】:WebClient.UploadFile failed with "The request was aborted: The request was canceled."WebClient.UploadFile 失败并显示“请求已中止:请求已取消。”
【发布时间】:2011-08-15 03:29:10
【问题描述】:

我正在尝试使用WebClient.UploadFile 将文件上传到 HTTP URL。对于1M、2M等小文件,上传成功。但是对于12M这样的大文件,我得到了这个异常:

The request was aborted: The request was canceled.

以前有没有人遇到过这个问题,你能分享一下解决方案吗?

一些信息:

  • 服务器正在使用 ASP.NET 3.5。
  • 我上传时使用的 HTTP 方法是“PUT”。

【问题讨论】:

  • 接收服务器是否配置为接受这么大的请求?例如,大多数 ASP.NET 网站的默认值为 4 MB。见msdn.microsoft.com/en-us/library/…
  • 谢谢 Tejs。我现在解决了这个问题。

标签: web-applications


【解决方案1】:

这是 smwikipedia 的答案中提到的解决方案。我添加了禁用写入流缓冲的功能,这有助于解决内存不足异常。

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
    }
}

用法:

var webClient = new ExtendedWebClient();
webClient.Timeout = Timeout.Infinite;
webClient.AllowWriteStreamBuffering = false;
webClient.UploadFile(url, filePath);

【讨论】:

  • 感谢改进。我更改为将您的标记为答案。
【解决方案2】:

我根据这里解决了: Extend the timeout value of WebClient

顺便说一句,由于 WebClient 的缓冲而导致 OutOfMemory 异常: Are you getting OutOfMemoryExceptions when uploading large files?

【讨论】:

    猜你喜欢
    • 2012-07-19
    • 2014-08-22
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多