尝试从Web API下载zip文件时出现错误“任务已取消”。我究竟做错了什么 ?


  说明:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息。
  
  异常详细信息:System.Threading.Tasks.TaskCanceledException:任务已取消。


using (var ms = new MemoryStream())
{
    using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
    {
        foreach (var attachment in item)
        {
            var entry = zipArchive.CreateEntry(attachment.ItemAnalisado.Arquivo.Nome, CompressionLevel.Fastest);
            using (var stream = entry.Open())
            {
                var dadosArquivo = File.ReadAllBytes(
                Path.Combine(CaminhoImagens,
                attachment.ItemAnalisado.Arquivo.ProcessoId.ToString(),
                attachment.ItemAnalisado.Arquivo.SubPastaId.ToString(),
                attachment.ItemAnalisado.Arquivo.Id.ToString()));
                stream.Write(dadosArquivo, 0, dadosArquivo.Length);
                //stream.Position = 0;
                stream.Close();
            }
        }
    }
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    ms.Position = 0;
    response.Content = new StreamContent(ms);
    ms.Dispose();
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = "teste.zip";
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
    return response;
}

最佳答案

尝试下载调用我的API的Excel文件时出现此错误。我没有在此方法上实施ATP,因此一开始令人感到困惑。这是我的初始代码:

public IHttpActionResult Get([FromUri] string id, [FromUri] SurveyReportRequestType requestType) {
    byte[] excelData = System.Text.Encoding.UTF8.GetBytes("Boobs out!");
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    using (var stream = new MemoryStream(excelData))
    {
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "Data.xls"
        };
    }
    return ResponseMessage(result);
}


经过思考并进行了一些更改,结果出来了:

...

byte[] excelData = System.Text.Encoding.UTF8.GetBytes("Boobs aout!");

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(excelData);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "Data.xls"
};
return ResponseMessage(result);


...

如您所见,我将流包含在using语句中。由于内容不可用于响应,这导致请求未完成。

07-24 09:30